原生javascript移动端滑动banner效果
程序员文章站
2023-12-03 08:32:22
本文实例为大家分享了移动端滑动banner效果的具体代码,供大家参考,具体内容如下
本文实例为大家分享了移动端滑动banner效果的具体代码,供大家参考,具体内容如下
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta content="telephone=yes" name="format-detection" /> <meta name="apple-mobile-web-app-status-bar-style" content="white"> <meta name="x5-fullscreen" content="true"> <meta name="apple-touch-fullscreen" content="yes"> <title>document</title> <style> *{margin:0;padding:0;} .box{ height:200px; width:100%; overflow: hidden; } .movebox{ height:200px; width:9000px; padding:0; position:relative; left:0; } .movebox li{ height:200px; float:left; list-style:none; font-size:30px; color:#fff; } </style> <script> window.onload = function(){ var movex, //手指滑动距离 endx, //手指停止滑动时x轴坐标 cout = 0, //滑动计数器 movedir; //滑动方向 var movebox = document.queryselector(".movebox"); //滑动对象 var li = movebox.queryselectorall("li"); //滑动对象item var width = parseint(window.getcomputedstyle(movebox.parentnode).width); //滑动对象item的宽度 movebox.style.width = (width*4) + "px"; //设置滑动盒子width for(var i = 0; i < li.length; i++){ li[i].style.width = width + "px"; //设置滑动item的width,适应屏幕宽度 } //触摸开始 function boxtouchstart(e){ var touch = e.touches[0]; //获取触摸对象 startx = touch.pagex; //获取触摸坐标 endx = parseint(movebox.style.webkittransform.replace("translatex(", "")); //获取每次触摸时滑动对象x轴的偏移值 } function boxtouchmove(e){ var touch = e.touches[0]; movex = touch.pagex - startx; //手指水平方向移动的距离 if(cout == 0 && movex > 0){ //刚开始第一次向左滑动时 return false; } if(cout == 3 && movex < 0){ //滑动到最后继续向右滑动时 return false; } movebox.style.webkittransform = "translatex(" + (endx + movex) + "px)"; //手指滑动时滑动对象随之滑动 } function boxtouchend(e){ movedir = movex < 0 ? true : false; //滑动方向大于0表示向左滑动,小于0表示向右滑动 //手指向左滑动 if(movedir){ if(cout<3){ movebox.style.webkittransform = "translatex(" + (endx-width) + "px)"; cout++; } //手指向右滑动 }else{ //滑动到初始状态时返回false if(cout == 0){ return false; }else{ movebox.style.webkittransform = "translatex(" + (endx+width) + "px)"; cout--; } } } //滑动对象事件绑定 movebox.addeventlistener("touchstart", boxtouchstart, false); movebox.addeventlistener("touchmove", boxtouchmove, false); movebox.addeventlistener("touchend", boxtouchend, false); } </script> </head> <body style="position:absolute;width:100%;overflow:hidden;"> <div class="box"> <ul class="movebox" style="transition-duration:0.2s;transform: translatex(-0px);"> <li style="background:red;">1</li> <li style="background:yellow">2</li> <li style="background:blue">3</li> <li style="background:green">4</li> </ul> </div> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。