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