封装一个移动端的click事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div{
            width: 180px;
            height: 180px;
            background-color: hotpink; 
        }
    </style>
</head>
<body>
    <div></div>

    <script>
        var div = document.querySelector('div');
        div.addEventListener('click',function(){
            console.log('click');
        })
        // 移动端大概有300ms左右的延迟,是移动端为了兼容双击操作 .
        // 如果300ms只点击了一次就是单击 如果点击2次就是双击
        // 使用touch事件模拟一个移动端的单击事件一般这个名称(tap)轻触事件

        function tap(dom,callback) {  
            // 是否触发了滑动中的事件
            var isMove = false;
            dom.addEventListener('touchstart',function (e) {  

            });
            dom.addEventListener('touchend',function (e) {  
                // 当触发了滑动中的事件
                isMove = true;
            });
            dom.addEventListener('touchend', function (e) {  
                if(isMove == false) {
                    // 就是一个点击操作. 执行回调函数
                    callback();
                }
                // 每次点击完毕重置isMove
                isMove = false;
            });
        }
        tap(div,function () {  
            console.log("这是移动端的tap事件");
        })
    </script>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容