fastclick原理剖析及其用法

移動端點擊延遲事件

    1. 移動端瀏覽器在派發點擊事件的時候,一般會出現300ms左右的延遲。
    2. 緣由: 移動端的雙擊會縮放致使click判斷延遲。
      這是爲了檢查用戶是否在作雙擊。爲了可以當即響應用戶的點擊事件,纔有了FastClick。

解決方式

    1. 禁用縮放 <meta name = "viewport" content="user-scalable=no" > 
      缺點: 網頁沒法縮放javascript

    2. 更改默認視口寬度 <meta name="viewport" content="width=device-width"> 
      缺點: 須要瀏覽器的支持css

    3. css touch-action touch-action的默爲 auto,將其置爲 none 便可移除目標元素的 300 毫秒延遲 缺點: 新屬性,可能存在瀏覽器兼容問題html

    4. tap事件 zepto的tap事件, 利用touchstart和touchend來模擬click事件
      缺點: 點擊穿透vue

    5. fastclick 原理: 在檢測到touchend事件的時候,會經過DOM自定義事件當即出發模擬一個click事件,並把瀏覽器在300ms以後真正的click事件阻止掉
      缺點: 腳本相對較大java

使用:

//JS    
// 引入   
<script type='application/javascript' src='/path/to/fastclick.js'></script>    
// 使用了jquery的時候    
$(function() {        FastClick.attach(document.body);    });    
// 沒使用jquery的時候    
if ('addEventListener' in document) {        
document.addEventListener('DOMContentLoaded', 
function() {            
FastClick.attach(document.body);        
}, false);}    

 在vue中使用 :

//js    
// 安裝    
npm install fastclick -S    
// 引入    
import FastClick from 'fastclick'    
// 使用    
FastClick.attach(document.body);

不須要使用fastclick的狀況

如下這幾種狀況是不須要使用fastclick:node

一、FastClick是不會對PC瀏覽器添加監聽事件
二、Android版Chrome 32+瀏覽器,若是設置viewport meta的值爲width=device-width,這種狀況下瀏覽器會立刻出發點擊事件,不會延遲300毫秒。jquery

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

三、全部版本的Android Chrome瀏覽器,若是設置viewport meta的值有user-scalable=no,瀏覽器也是會立刻出發點擊事件。
四、IE11+瀏覽器設置了css的屬性touch-action: manipulation,它會在某些標籤(a,button等)禁止雙擊事件,IE10的爲-ms-touch-action: manipulationios

 

問題BUG

引入fastclick.js ,ios點擊輸入框以後,點擊軟鍵盤上的 完成 時發現,輕擊input就沒法喚起軟鍵盤,沒法對輸入框聚焦,必須長按或重壓才行,ios11 後修復了移動點擊300ms延遲git

解決方法:在node_module裏找到fastClick文件github

FastClick.prototype.focus = function(targetElement) {
        var length;

        // Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
        if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') {
            length = targetElement.value.length;
            targetElement.setSelectionRange(length, length);
            //修復bug ios11.3以上版本不彈出鍵盤,這裏加上聚焦代碼,讓其強制聚焦彈出鍵盤
 targetElement.focus();
        } else {
            targetElement.focus();
        }
    };

 另一種思路是 在 每個input 強制加一個點擊事件,點擊後,聚焦 focus 便可。

參考:https://github.com/ftlabs/fastclick

相關文章
相關標籤/搜索