移动端常见问题(click 300ms延迟)

根本原因:double click 双击

移动端默认双击情况下会有方法效果,当你点击一次之后,移动端无法判断你是否下一次还会继续完成双击,因此存在300 ms 延迟

 

有一部分浏览器,比如chrome浏览器,当你在meta头设置width=device-width时,它会自动禁止300 ms的延迟

推荐的解决方法:fastclick https://github.com/ftlabs/fastclick

原理:当检测到touchend事件后,会触发自己模拟的click事件

 

先测试一下touchstart和click之间的时间差:

我用的chrome

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>移动端动画</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
    <style>
        *{padding:0;margin:0;}
        .box{width:100px;height: 100px;background-color: pink;}
    </style>
</head>
<body>
    <div class="box" id="box"></div>

    <script>
        
        var box=document.getElementById("box"),
            startTime=0;

            box.addEventListener("touchstart",function(){
                startTime=Date.now();//获取当前时间
                console.log("touchstart");
            },false);    

            box.addEventListener("click",function(){
                console.log("click");
                console.log(Date.now()-startTime);
            },false);    

    </script>
</body>
</html>

 

 这个88ms的时间差延迟是可以接受的,说明chrome浏览器已经解决了这个问题

 

但是有部分浏览器比如安卓机上的还是会存在300ms延迟问题

 

 

解决方法:首先引入fastclick.js

<script src="fastclick.js"></script>

然后添加这段代码:

<script>
        if ('addEventListener' in document) {
            document.addEventListener('DOMContentLoaded', function() {
                FastClick.attach(document.body);
            }, false);
        }
    </script>

 

 jQuery版需要用下面这段代码:

$(function() {
    FastClick.attach(document.body);
});

 

以下这几种情况是不需要使用fastclick:

1、FastClick不会对PC浏览器添加监听事件
2、Android版Chrome 32+浏览器,如果设置viewport meta的值为width=device-width,这种情况下浏览器会马上出发点击事件,不会延迟300毫秒。

<meta name="viewport" content="width=device-width, initial-scale=1">

 

3、所有版本的Android Chrome浏览器,如果设置viewport meta的值有user-scalable=no,浏览器也是会马上触发点击事件。
4、IE11+浏览器设置了css的属性touch-action: manipulation,它会在某些标签(a,button等)禁止双击事件,IE10的为-ms-touch-action: manipulation

posted @ 2020-03-17 13:38  陈莺莺呀  阅读(577)  评论(0编辑  收藏  举报