事件
常見的事件有:
| 類型 | 觸發條件 | 最低版本 |
|---|---|---|
| touchstart | 手指觸摸動作開始 | |
| touchmove | 手指觸摸后移動 | |
| touchcancel | 手指觸摸動作被打斷,如來電提醒,彈窗 | |
| touchend | 手指觸摸動作結束 | |
| tap | 手指觸摸后馬上離開 | |
| longpress | 手指觸摸后,超過350ms再離開,如果指定了事件回調函數並觸發了這個事件,tap事件將不被觸發 | 1.5.0 |
| longtap | 手指觸摸后,超過350ms再離開(推薦使用longpress事件代替) | |
| transitionend | 會在 WXSS transition 或 wx.createAnimation 動畫結束后觸發 | |
| animationstart | 會在一個 WXSS animation 動畫開始時觸發 | |
| animationiteration | 會在一個 WXSS animation 一次迭代結束時觸發 | |
| animationend | 會在一個 WXSS animation 動畫完成時觸發 | |
| touchforcechange | 在支持 3D Touch 的 iPhone 設備,重按時會觸發 |
有兩個注意點:
Touchcancle: 在某些特定場景下才會觸發(比如來電打斷等)
tap事件和longpress事件通常只會觸發其中一個
tap 點擊事件
當視圖層發生事件時,某些情況需要事件攜帶一些參數到執行的函數中, 這個時候就可以通過
data-屬性來完成:
1 格式:data-屬性的名稱
2 獲取:e.currentTarget.dataset.屬性的名稱
eg:
test.wxml
# tap 點擊事件 <button bind:tap='click' data-name="{{name}}" data-age="20">按鈕</button>
test.js
Page({ data: { name: 'word', }, click: function (e) { // 參數 e 是整個事件 console.log(e) // 打印整個事件 // 從事件中獲取傳遞的參數 const data = e.currentTarget.dataset; console.log(data) // 打印 dataset 的值 }, ) // 參數 e 是整個事件 // 事件傳遞的參數都在 currentTarget.dataset 中

touches和changedTouches的區別

事件傳遞與冒泡
test.js
page({ click1: function () { console.log("外面的") }, click2: function () { console.log("中間的") } , click3: function () { console.log("里面的") }, cap1: function () { console.log("傳遞,外面的") }, cap2: function () { console.log("傳遞,中間的") } , cap3: function () { console.log("傳遞,里面的") }, })
傳遞 capture-bind:tap="cap1"
test.wxml
<!--事件傳遞--> <view class="outer" capture-bind:tap="cap1">外面 <view class="midder" capture-bind:tap="cap2">中間的 <view class="inner" capture-bind:tap="cap3">里面 </view> </view> </view>

冒泡 bind:tap="click1"
<!--事件冒泡--> <view class="outer" bind:tap="click1" >外面 <view class="midder" bind:tap="click2" >中間的 <view class="inner" bind:tap="click3" >里面 </view> </view> </view>

阻止事件傳遞與冒泡 catch
<!--阻止事件傳遞與冒泡--> <view class="outer" bind:tap="click1" capture-bind:tap="cap1">外面 <view class="midder" catch:tap="click2" capture-bind:tap="cap2">中間的 <view class="inner" bind:tap="click3" capture-catch:tap="cap3">里面 </view> </view> </view>

注: 摘自 小猿取經
