zoukankan      html  css  js  c++  java
  • 移动端tap事件(轻击、轻触)

    一、问题

    ①移动端也有click点击事件,click点击会延迟200~300ms

    ②因为点击的响应过慢,影响了用户体验,所以需要解决响应慢的问题

    二、解决方案

    ①使用tap事件:即轻击,轻敲,响应速度快(不是原生事件,是通过touch相关事件衍生过来的

    <!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>tap事件</title>
        <style>
            .body{
                margin: 0;
                padding: 0;
            }
            .box{
                width: 200px;
                height: 200px;background: #ccc;
                float: left;
            }
        </style>
    </head>
    <body>
        <div class="box"></div>
        <script>
            window.onload=function(){
                // 封装事件
                bindTapEvent=function(dom,tapCallback,clickCallback){
                    var startTime=0;
                    var isMove=false;
                    dom.addEventListener('touchstart',function(e){
                        startTime=Date.now()
                    });
                    dom.addEventListener('touchmove',function(e){
                        isMove=true
                    });
                    dom.addEventListener('touchend',function(e){
                        
                        if((Date.now()-startTime)<150 && isMove){
                            // 假设点击的时间间隔小于150ms为轻击事件
                            tapCallback && tapCallback.call(this,e)
                        }else{
                            // 假设点击的时间间隔大于150ms为点击事件
                            clickCallback && clickCallback.call(this,e)
                        }
                        startTime=0;
                        isMove=false;
                    });
                }
                // 调用
                bindTapEvent(document.querySelector('.box'),function(e){
                    console.log('tap事件')
                },function(e){
                    console.log('click事件')
                })
            }
        </script>
    </body>
    </html>

    ②使用fastclick.js插件:可以提高移动端click响应速度,下载地址:https://github.com/ftlabs/fastclick

        <script src="fastclick.js"></script>
        <script>
            // 当页面的dom元素加载完成
            document.addEventListener('DOMContentLoaded',function(){
                // 初始化方法
                FastClick.attach(document.body);
            },false);
            // 正常使用click事件即可
        </script>

    具体用法可以参考:

  • 相关阅读:
    在Visual Studio中使用NUnit
    C#调用Exe
    网页用chrome打开为乱码
    ctags最基本用法
    Facebook Connect
    SVM初体验
    python中可恶的回车符
    初识PowerDesigner
    Mysql中文乱码问题解决
    stat函数
  • 原文地址:https://www.cnblogs.com/EricZLin/p/9334821.html
Copyright © 2011-2022 走看看