天天看點

4. js移動端點觸(tap)事件

  1. 移動端本身就有click事件,但是該事件在touch事件之後發生,延遲時間為300ms,影響使用者體驗
  2. tap事件(不是移動端原生事件,通過touch相關事件衍生過來)
  3. 使用tap事件,響應的速度比click要快
  4. fastclick.js可以提高移動端click響應速度
    <!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 bindTapEvent = function(dom, callback){
                    var isMove = false; //是否滑動
                    var startTime = 0; //點觸開始時間
    
                    dom.addEventListener("touchstart", function(e){
                        startTime = Date.now();
                    });
    
                    dom.addEventListener("touchmove", function(e){
                        isMove = true;
                    });
                    
                    dom.addEventListener("touchend", function(e){
                        //時間小于150ms,并且沒有滑動才認為是點觸事件
                        if((Date.now() - startTime < 150) && !isMove){
                            callback && callback.call(this, e);
                        }
                    });
    
                    /*dom.addEventListener('click',function () {
                    //console.log('click');
                    });*/
                }
    
    
                bindTapEvent(document.querySelector(".box"), function(e){
                    console.log("點觸");
                    console.log(this);
                    console.log(e);
                });
            }
            
        </script>
    </body>
    </html>
    	
               

繼續閱讀