3.js移动端滑动手势

  1. 只对触摸手势起作用,不能鼠标控制

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>滑动手势</title>
        <style type="text/css">
            .box{
                width:300px;
                height:300px;
                background-color: pink;
            }
        </style>
    </head>
    <body>
        <div class="box"></div>
    
        <script>
            window.onload = function(){
                var bindSwipeEvent = function(dom, leftSwipeCallback, rightSwipeCallback){
                    var isMove = false; //是否位移
                    var startX = 0; //起始位置
                    var moveX = 0; //移动距离,距离大于50px认为是滑动
    
                    dom.addEventListener("touchstart", function(e){
                        startX = e.touches[0].clientX;
                    });
    
                    dom.addEventListener("touchmove", function(e){
                        isMove = true;
                        moveX = e.touches[0].clientX - startX;
                    });
    
                    dom.addEventListener("touchend", function(e){
                        if(isMove && Math.abs(moveX) > 50){
                            if(moveX < 0){
                                leftSwipeCallback && leftSwipeCallback.call(this, e);
                            }else{
                                rightSwipeCallback && rightSwipeCallback.call(this, e);
                            }
                        }
    					//重置变量
    					isMove = false; 
    		            startX = 0; 
    		            moveX = 0; 
                    });				
                }
    
                bindSwipeEvent(document.querySelector(".box"), function(e){
                    console.log("左滑动");
                    console.log(this);
                    console.log(e);
                }, function(e){
                    console.log("右滑动");
                    console.log(this);
                    console.log(e);
                });
            }
        </script>
    </body>
    </html>
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值