移動端300ms與點透總結

300ms,主要發生在mobile

  1. 爲啥會出現300ms延遲現象
    • 瀏覽器想知道用戶是否dobule tap(雙擊縮放)
  2. 下列狀況不會出現300ms延遲
    • 桌面瀏覽器
    • meta的viewport設置了user-scalable=no(禁止縮放)
    • meta的viewport設置了width或者initial-scale
    • IE11+,設置了touch-action: manipulation;.For IE10 use -ms-touch-action: manipulation;

移動端點透

發生狀況:html

  1. A,B兩個層上下重疊在Z軸中
  2. 綁定touchstart/touchend事件,使上層的A點擊後消失
  3. B默認有click事件或B綁定了click事件

爲何會產生點透:瀏覽器

  1. 移動端事件執行順序:touchstart -> touchend -> click

解決方案:app

  1. 儘可能用touch事件替換click事件
  2. 阻止a標籤的click的狀況:在消失元素的touchstart/touchend事件,調用event.preventDefault或者event.returnValue = false
  3. A和B都用click事件作綁定
  4. fastclick原理(在body中綁定監聽事件,而後作出判斷,是否須要調用preventDefault來處理)

如下爲demo,跑一遍就能懂大概原理

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!-- wipe 300ms delay -->
    <!-- Instead of above code, your can see div2 has 300ms delay -->
    <meta name="viewport" content="user-scalable=no, initial-scale=1.0">
    <style>
        *{
            margin: 0px;
            padding:0px;
        }
        #div1{
            width: 300px;
            height: 300px;
            background-color: rgba(255,0,0,0.25);        
        }
        #div2{
            width: 240px;
            height: 240px;
            background-color: yellow;
            position: absolute;
            left: 30px;
            top: 30px;
            z-index: -1;
        }
        #console{
            border: 1px solid green;
            position: absolute;
            top: 300px;
            width: 100%;
        }
    </style>
</head>
<body>
    <div id="div1"></div>
    <div id="div2">
       <a href="http://www.baidu.com">jump to baidu.com</a>
    </div>
    <div id="console"></div>
    <script>
        $ = function (id) {return document.getElementById(id)}
        var div1 = $("div1");
        var div2 = $('div2');
        var con = $('console');
        var sDate, eDate;

        function handle(e){
            // computed time interval
            if (sDate == null) {
                sDate = (new Date).getTime()
            }
            eDate = (new Date).getTime()

            var tar = e.target,
          eve = e.type;
            
            // prevent 點透
            if(eve == "touchend") {
                console.log(tar)
                e.preventDefault();
            }

            var ele = document.createElement("p");
            ele.innerHTML = "target:"+ tar.id + " event:" + eve + ' interval: ' + (eDate-sDate) + 's';
            con.appendChild(ele);
            if(tar.id === "div1"){ 
                div1.style.display = "none";
            }
        }
        div1.addEventListener("touchend",handle);
        div1.addEventListener("touchstart",handle);
        div2.addEventListener("click",handle);
    </script>
</body>
</html>
相關文章
相關標籤/搜索