点击延迟_解决移动端浏览器点击延迟300ms的问题——FastClick用法
為什么要使用FastClick
移動設(shè)備上的瀏覽器默認(rèn)會在用戶點擊屏幕大約延遲300毫秒后才會觸發(fā)點擊事件,這是為了檢查用戶是否在做雙擊。為了能夠立即響應(yīng)用戶的點擊事件,才有了FastClick。
項目地址:
ftlabs/fastclick?github.comFastClick的使用
安裝fastclick
安裝fastclick可以使用npm,Component和Bower。另外也提供了Ruby版的gem fastclick-rails以及.NET提供了NuGet package。最直接的可以在頁面引入fastclick js文件。如:
- 在頁面直接引入fastclick.js
- 使用npm安裝
初始化FastClick實例
初始化FastClick實例建議在頁面的DOM文檔加載完成后。
- 純Javascript版
- jQuery版
- 類似Common JS的模塊系統(tǒng)方式
調(diào)用require('fastclick')會返回FastClick.attach函數(shù)。
使用needsclick過濾特定的元素
如果頁面上有一些特定的元素不需要使用fastclick來立刻觸發(fā)點擊事件,可以在元素的class上添加needsclick:
<a class="needsclick">Ignored by FastClick</a>不需要使用fastclick的情況
以下這幾種情況是不需要使用fastclick:
1、FastClick是不會對PC瀏覽器添加監(jiān)聽事件
2、Android版Chrome 32+瀏覽器,如果設(shè)置viewport meta的值為width=device-width,這種情況下瀏覽器會馬上出發(fā)點擊事件,不會延遲300毫秒。
<meta name="viewport" content="width=device-width, initial-scale=1">3、所有版本的Android Chrome瀏覽器,如果設(shè)置viewport meta的值有user-scalable=no,瀏覽器也是會馬上出發(fā)點擊事件。
4、IE11+瀏覽器設(shè)置了css的屬性touch-action: manipulation,它會在某些標(biāo)簽(a,button等)禁止雙擊事件,IE10的為-ms-touch-action: manipulation
存在的問題
有一個問題,就是input的焦點很難獲取,往往需要多次點擊或者雙擊才能獲取到焦點(大家可以去試試,真的很難點),最開始以為是獲取焦點區(qū)域太小導(dǎo)致,后來發(fā)現(xiàn)是這個fastclick.js框架的問題。
解決方法:
SO,我們點開源碼,找到這一段
/*** @param {EventTarget|Element} targetElement*/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' && targetElement.type !== 'email') {length = targetElement.value.length;targetElement.focus(); // 加入這一句話就OK了targetElement.setSelectionRange(length, length);} else {targetElement.focus();}};總結(jié)
以上是生活随笔為你收集整理的点击延迟_解决移动端浏览器点击延迟300ms的问题——FastClick用法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 招商银行信用卡年费多少
- 下一篇: 平常人怎么能贷30万