代码描述:JavaScript 移动端触屏 拖动页面 滚动效果。JavaScript移动端触屏拖动页面滚动效果
分享一段代码实例,它利用原生js实现了移动端触屏拖动页面滚动效果。 代码实例如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.51qianduan.com/" /> <title>51前端</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>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能