移动端事件使用中遇到的问题(click延迟,点透)

一、click在手机上的延迟问题(300ms左右)

1. 加上视口

width=device-width  解决苹果

user-scalable = no  解决安卓

<meta name="viewport" content="width=device-width, initial-scale=1.0 , user-scalable = no">

2. 使用fastclick.js

去BootCDN下载一下fastClick.js,然后在js里写上FastClick.attach(document.body);

<script src="./js/fastclick.js"></script>
<script>
     FastClick.attach(document.body);
</script>

3. 使用zepto.js 中的tap事件

使用的时候载入zepto.js和touch.js

<script src="./js/zepto.js"></script>
<script src="./js/touch.js"></script>
<script>
    window.onload = function () {
       $("div").on("tap",function(){
           //这里写点击事件要执行的代码
        })
    }


</script>

注:在这里我想说明一下事件的执行顺序是:touchstart > touchend > click

示例:

<body>
    <div class="box" style="width: 200px;height: 200px;background-color: #ccc;"></div>

    <script>
        
        var oBox = document.querySelector(".box")

        oBox.addEventListener("click",function(){
            console.log("click")
        })
        oBox.addEventListener("touchstart",function(){
            console.log("touchstart")
        })
        oBox.addEventListener("touchmove",function(){
            console.log("touchmove")
        })
        oBox.addEventListener("touchend",function(){
            console.log("touchend")
        })
    
    </script>
</body>

最终的结果如图:

 

二、移动端的点透问题

点透问题的发生原因是,在点击的时候上面层消失的太快,导致下面的元素也会被点击,其解决方案有:
1. fastclick.js

2. 使用viewport

3. zepto

以上三种方法的使用前面已经说过,就不再重复。

4. 绑定相同的事件

//使用这种方法点击div这个遮罩层的时候就不会触发h元素的alert事件
var oDiv = document.querySelector("div")
var h = document.querySelector("h1")
oDiv.addEventListener("touchstart",function(){
     this.style.display = "none"
})

h.addEventListener("touchstart",function(){
   alert("h1")
})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值