原生js左右滑动

<html lang="en">
<head>
        <meta charset="UTF-8">
      <title>   </title>
</head>
<style type="text/css">
  .box{
               width:100%;
             height: 100%;
           position: fixed;
            margin:auto;
                top: 0;
             left: 0;
            right:0;
            bottom: 0;
          background: red;
                opacity: 0.6;
               color: black;
   }
</style>
<body>
     <div class="box" id="box">dssdfsdfsdffffffffffffffffffffffffffffffffs</div>
</body>
<script type="text/javascript">
     function _touch(){
              var startx;//让startx在touch事件函数里是全局性变量。
              var endx;
               var el=document.getElementById('box');
              function cons(){   //独立封装这个事件可以保证执行顺序,从而能够访问得到应该访问的数据。
                     console.log(starty,endy);
                   //var l=Math.abs(startx-endx);
                  //var h=Math.abs(starty-endy);
                  //if(l>h){
                               //x事件
                           //if(startx>endx){
                                       //alert('left');
                                //}else{
                                        //alert('right');
                               //}
                     //}else{
                                //y事件
                           //if(starty>endy){
                                       //alert('top');
                         //}else{
                                        //alert('bottom');
                              //}
                     //}
                     if(startx>endx){  //判断左右移动程序
                            alert('left');
                      }else{
                          alert('right');
                     }
               }
               el.addEventListener('touchstart',function(e){
                       var touch=e.changedTouches;
                     startx=touch[0].clientX;
                    starty=touch[0].clientY;
            });
             el.addEventListener('touchend',function(e){
                 var touch=e.changedTouches;
                     endx=touch[0].clientX;
                      endy=touch[0].clientY;
                      cons();  //startx endx 的数据收集应该放在touchend事件后执行,而不是放在touchstart事件里执行,这样才能访问到touchstart和touchend这2个事件产生的startx和endx数据。另外startx和endx在_touch事件函数里是全局性的,所以在此函数中都可以访问得到,所以只需要注意事件执行的先后顺序即可。
           });
     }
       _touch()
</script>
</html>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值