原創聲明:本文為作者原創,未經允許不得轉載,經授權轉載需注明作者和出處
》》》什么是事件(官方文檔)
》》》事件分類
》》》事件綁定
事件綁定的寫法同組件的屬性,以 key、value 的形式。
上面簡單介紹了小程序事件基礎,是時候彰顯”事件”的威力:
1.單擊
單擊事件由touchstart、touchend組成,touchend后觸發tap事件。
<view>
<button type="primary" bindtap="mytap">點我吧</button>
</view>
mytap: function(e){
console.log(e.timeStamp + '- tap')
}
2.雙擊
雙擊事件由兩個單擊事件組成,兩次間隔時間小于300ms認為是雙擊;微信官方文檔沒有雙擊事件,需要開發者自己定義處理。
<view>
<button type="primary" bindtap="mytap">點我吧</button>
</view>
//觸摸事件,判斷單擊還是雙擊
mytap: function(e){
var curTime = e.timeStamp;
var lastTime = this.data.lastTapDiffTime;
if(lastTime > 0){
//如果兩次單擊間隔小于300毫秒,認為是雙擊
if(curTime - lastTime < 300){
console.log(e.timeStamp + '- db tap')
}else{
console.log(e.timeStamp + '- tap')
}
}else{
console.log(e.timeStamp + '- first tap')
}
this.setData({lastTapDiffTime: curTime});
}
3.長按
長按事件手指觸摸后,超過350ms再離開。
<view>
<button type="primary" bindlongtap="mylongtap">點我吧</button>
</view>
//長按事件
mylongtap: function(e){
console.log(e.timeStamp + '- long tap')
}
單擊、雙擊、長按屬于點觸事件,會觸發touchstart、touchend、tap事件;touchcancel事件在真機方便測試,這里就不多說了。
事件 | 觸發順序 |
---|---|
單擊 | touchstart → touchend → tap |
雙擊 | touchstart → touchend → tap → touchstart → touchend → tap |
長按 | touchstart → longtap → touchend → tap |
4.滑動
目前官方沒有提供左右滑事件,復雜的手勢(多點旋轉、多點縮放,多點平移)也需要我們自己通過代碼實現。
5.多點觸控
多點觸控,只有在真機條件下才可測試,已測試。
@Roluce 童鞋已經發帖講述了,詳見新手必‘暈’的changedTouches,您肯定不知道的!(框架細節十二)
以上簡單的介紹小程序的基本事件類型和使用,復雜的手勢控制可以有多個基本觸控事件組合而成。后面篇章還會繼續深入學習事件冒泡、通過綁定事件傳參數、復雜手勢控制實現。