微信小程序 觸控事件:
微信小程序的"事件"挺有意思。看了說明文檔后發現它的功能很全,事件可以向父節點傳遞,而且打印這個事件的信息很透明,調試起來應該非常方便。
接下來把文檔copy過來
原文地址:https://mp.weixin.qq.com/debug/wxadoc/dev/framework/view/wxml/event.html
》》》什么是事件
事件的使用方式
在組件中綁定一個事件處理函數。
如bindtap,當用戶點擊該組件的時候會在該頁面對應的Page中找到相應的事件處理函數。
<view id="tapTest" data-hi="MINA" bindtap="tapName"> Click me! </view>
在相應的Page定義中寫上相應的事件處理函數,參數是event。
Page({ tapName: function(event) { console.log(event) } }) 可以看到log出來的信息大致如下:
{ "type": "tap", "timeStamp": 1252, "target": { "id": "tapTest", "offsetLeft": 0, "offsetTop": 0, "dataset": { "hi": "MINA" } }, "currentTarget": { "id": "tapTest", "offsetLeft": 0, "offsetTop": 0, "dataset": { "hi": "MINA" } }, "touches": [{ "pageX": 30, "pageY": 12, "clientX": 30, "clientY": 12, "screenX": 112, "screenY": 151 }], "detail": { "x": 30, "y": 12 } } 事件詳解
事件分類
事件分為冒泡事件和非冒泡事件:
冒泡事件:當一個組件上的事件被觸發后,該事件會向父節點傳遞。
非冒泡事件:當一個組件上的事件被觸發后,該事件不會向父節點傳遞。
》》》事件分類
》》》事件綁定
事件綁定的寫法同組件的屬性,以 key、value 的形式。
上面簡單介紹了小程序事件基礎,是時候彰顯"事件"的威力:
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組成

坐標圖:

以上沒考慮r為1的情況。
<view> <button type="primary" bindtouchstart="mytouchstart" bindtouchmove="mytouchmove">點我吧</button></view>

5.多點觸控
由于模擬器尚不支持多點觸控,內測開放后,繼續補充。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答