移動端觸屏拖動頁面滾動效果

admin發表於2017-02-22

分享一段程式碼例項,它利用原生js實現了移動端觸屏拖動頁面滾動效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
* {
  margin: 0;
  padding: 0;
}
.containerWrap {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  overflow: hidden;
}
.container {
  width: 100%;
  -webkit-transition: all .6s ease-in-out;
  transition: all .6s ease-in-out;
}
.slideItem {
  width: 100%;
}
.slideItem1 {
  background: #f00;
}
.slideItem2 {
  background: #0f0;
}
.slideItem3 {
  background: #00f;
}
</style>
</head>
<body>
<div class="containerWrap">
  <div class="container">
    <div class="slideItem slideItem1"></div>
    <div class="slideItem slideItem2"></div>
    <div class="slideItem slideItem3"></div>
  </div>
</div>
<script>
var containerWrap = document.querySelector(".containerWrap");
var container = containerWrap.querySelector(".container");
var slideItem = container.querySelectorAll(".slideItem");
var slideLength = slideItem.length;
var wrapHeight = containerWrap.offsetHeight;
container.setAttribute("style", "height:" + wrapHeight * slideLength + "px");
for (var i = 0; i < slideLength; i++) {
  slideItem<i>.setAttribute("style", "height:" + wrapHeight + "px");
}
var FullPage = {
  pageIndex: 1,
  isScrolling: false,
  nextPage: function() {
    if (this.pageIndex + 1 > slideLength) {
      return false;
    } else {
      this.pageIndex += 1;
      this.scrollPage(this.pageIndex);
    }
  },
  prevPage: function() {
    if (this.pageIndex - 1 <= 0) {
      return false;
    } else {
      this.pageIndex -= 1;
      this.scrollPage(this.pageIndex);
    }
  },
  scrollPage: function(index) {
    // isScrolling 動畫進行時鎖定
    FullPage.isScrolling = true;
    var rollingDistance = -(index - 1) * wrapHeight + "px";
    container.setAttribute("style", "transform: translateY(" + rollingDistance + ")");
    container.addEventListener("transitionend", function() {
      // 動畫結束後釋放鎖定
      FullPage.isScrolling = false;
    }, false);
  },
  touchEvent: function(ele) {
    ele.addEventListener("touchstart", function(e) {
      var touch = e.touches[0];
      FullPage.touchStartY = touch.pageY;
    });
    ele.addEventListener("touchend", function(e) {
      if (FullPage.isScrolling) return;
      var touch = e.changedTouches[0];
      FullPage.touchEndY = touch.pageY;
      var diffY = FullPage.touchEndY - FullPage.touchStartY;
      if (Math.abs(diffY) > 50) {
        if (diffY > 0) {
          FullPage.prevPage();
        } else if (diffY < 0) {
          FullPage.nextPage();
        }
      }
    });
  },
  init: function() {
    this.touchEvent(container);
  }
};
document.addEventListener("DOMContentLoaded", function() {
  FullPage.init();
});                
</script>
</body>
</html></i>

相關文章