【未經作者本人同意,請勿以任何形式轉載】
》》》什么是事件
-
事件是視圖層到邏輯層的通訊方式。
-
事件可以將用戶的行為反饋到邏輯層進行處理。
-
事件可以綁定在組件上,當達到觸發事件,就會執行邏輯層中對應的事件處理函數。
-
事件對象可以攜帶額外信息,如id, dataset, touches。
》》》事件分類
-
touchstart 手指觸摸
-
touchmove 手指觸摸后移動
-
touchcancel 手指觸摸動作被打斷,如彈窗和來電提醒
-
touchend 手指觸摸動作結束
-
tap 手指觸摸后離開
-
longtap 手指觸摸后后,超過350ms離開
》》》事件綁定
事件綁定的寫法同組件的屬性,以 key、value 的形式。
-
key 以bind或catch開頭,然后跟上事件的類型,如bindtap, catchtouchstart
-
value 是一個字符串,需要在對應的 Page 中定義同名的函數。不然當觸發事件的時候會報錯。 bind事件綁定不會阻止冒泡事件向上冒泡,catch事件綁定可以阻止冒泡事件向上冒泡。
上面簡單介紹了小程序事件基礎,是時候彰顯"事件"的威力:
-
單擊(tap)
-
雙擊(dbtap)
-
長按(longtap)
-
滑動
-
多點觸控
1.單擊
單擊事件由touchstart、touchend組成,touchend后觸發tap事件。
<view>
<button type="primary" bindtouchstart="mytouchstart" bindtouchend="mytouchend" bindtap="mytap">點我吧</button> </view>
mytouchstart: function(e){ console.log(e.timeStamp + '- touch start') },mytouchend: function(e){ console.log(e.timeStamp + '- touch end') },mytap: function(e){ console.log(e.timeStamp + '- tap') }
2.雙擊
雙擊事件由兩個單擊事件組成,兩次間隔時間小於300ms認為是雙擊;微信官方文檔沒有雙擊事件,需要開發者自己定義處理。
<view>
<button type="primary" bindtap="mytap">點我吧</button> </view>
3.長按
長按事件手指觸摸后,超過350ms再離開。
<view>
<button type="primary" bindtouchstart="mytouchstart" bindlongtap="mylongtap" bindtouchend="mytouchend" bindtap="mytap">點我吧</button> </view>
mytouchstart: function(e){ console.log(e.timeStamp + '- touch start') },//長按事件mylongtap: function(e){ console.log(e.timeStamp + '- long tap') },mytouchend: function(e){ console.log(e.timeStamp + '- touch end') },mytap: function(e){ console.log(e.timeStamp + '- tap') }
單擊、雙擊、長按屬於點觸事件,會觸發touchstart、touchend、tap事件,touchcancel事件只能在真機模擬,不多說了。
事件 | 觸發順序 |
---|---|
單擊 | touchstart → touchend → tap |
雙擊 | touchstart → touchend → tap → touchstart → touchend → tap |
長按 | touchstart → longtap → touchend → tap |
4.滑動
手指觸摸屏幕並移動,為了簡化起見,下面以水平滑動和垂直滑動為例。 滑動事件由touchstart、touchmove、touchend組成
坐標圖:
-
以屏幕左上角為原點建立直角坐標系。第四象限為手機屏幕,Y軸越往下坐標值越大(注意跟數學象限的區別)。
-
假設A點為touchstart事件觸摸點,坐標為A(ax,ay),然后手指向上滑動到點B(bx,by),就滿足條件by < ay;
-
同理,向右滑動到C(cx,cy),滿足cx > ax;向下滑動到D(dx,dy),滿足dy > ay;向左移動到E(ex,ey)滿足ex < ax.
-
計算線段AB在Y軸上投影長度為m,在X軸上的投影長度為n
-
計算r = m/n,如果r > 1,視為向上滑動。
-
同理計算線段AC,AD,AE在Y軸投影長度與X軸的投影長度之比,得出向右向下向左的滑動。
以上沒考慮r為1的情況。
<view>
<button type="primary" bindtouchstart="mytouchstart" bindtouchmove="mytouchmove">點我吧</button> </view>
5.多點觸控
由於模擬器尚不支持多點觸控,內測開放后,繼續補充。
你也可以關注我的微信公眾號『ITNotes』, 一起交流學習 。