要實現雙擊的基本思路,就是通過touch來記錄時間,然后通過最后一次點擊時間減去touch的時間,如果時間小於300,就是雙擊時間,否則就是單擊時間
1.首先,需要在js中定義幾個變量
// 觸摸開始時間 touchStartTime: 0, // 觸摸結束時間 touchEndTime: 0, // 最后一次單擊事件點擊發生時間 lastTapTime: 0, // 單擊事件點擊后要觸發的函數 lastTapTimeoutFunc: null,
2.觸摸事件的函數
/// 按鈕觸摸開始觸發的事件 touchStart: function(e) { this.touchStartTime = e.timeStamp }, /// 按鈕觸摸結束觸發的事件 touchEnd: function(e) { this.touchEndTime = e.timeStamp },
3.在界面中需要綁定點擊事件的地方,需要加入bindtouchstart 和bindtouchend,以便記錄下按鈕開始觸摸和結束觸摸的時間。其他的分別綁定好單擊、雙擊、長按事件就好了。
<view class = "btn" bindtap="multipleTap" bindlongtap="longTap" bindtouchstart="touchStart" bindtouchend="touchEnd"> 單擊/雙擊/長按 </view>
4.單擊、雙擊和長按同時存在的實現:
/// 長按 longTap: function(e) { console.log("long tap") wx.showModal({ title: '提示', content: '長按事件被觸發', showCancel: false }) }, /// 單擊、雙擊 multipleTap: function(e) { var that = this // 控制點擊事件在350ms內觸發,加這層判斷是為了防止長按時會觸發點擊事件 if (that.touchEndTime - that.touchStartTime < 350) { // 當前點擊的時間 var currentTime = e.timeStamp var lastTapTime = that.lastTapTime // 更新最后一次點擊時間 that.lastTapTime = currentTime // 如果兩次點擊時間在300毫秒內,則認為是雙擊事件 if (currentTime - lastTapTime < 300) { console.log("double tap") // 成功觸發雙擊事件時,取消單擊事件的執行 clearTimeout(that.lastTapTimeoutFunc); wx.showModal({ title: '提示', content: '雙擊事件被觸發', showCancel: false }) } else { // 單擊事件延時300毫秒執行,這和最初的瀏覽器的點擊300ms延時有點像。 that.lastTapTimeoutFunc = setTimeout(function () { console.log("tap") wx.showModal({ title: '提示', content: '單擊事件被觸發', showCancel: false }) }, 300); } } },
參考鏈接:https://blog.csdn.net/h330531987/article/details/80651139