移動端頁面功能之——長按事件

朕知道了發表於2016-06-28

有時在做移動端頁面開發過程中遇到這種需求:“模擬指紋識別“
實際上我們只能通過長按頁面中的元素來模擬這個功能。
在jQuery和Zepto中都沒有包含長按事件,所以需要我們來擴充套件一下。

$.fn.longPress = function(fn) {
    var timeout = undefined;
    var $this = this;
    for(var i = 0;i<$this.length;i++){
        $this[i].addEventListener(`touchstart`, function(event) {
            timeout = setTimeout(fn, 800);  //長按時間超過800ms,則執行傳入的方法
            }, false);
        $this[i].addEventListener(`touchend`, function(event) {
            clearTimeout(timeout);  //長按時間少於800ms,不會執行傳入的方法
            }, false);
    }
}

首先要新增這段程式碼,然後呼叫:

$(`.object`).longPress(function(){
    //do something...
});

相關文章