iOS 你不知道的新鲜事iOS 开发成长中心

微信小程序 事件响应

2018-03-25  本文已影响15人  LYSNote

返回目录

微信小程序中事件分为冒泡事件和非冒泡事件:

  1. 冒泡事件:当一个组件上的事件被触发后,该事件会向父节点传递。
  2. 非冒泡事件:当一个组件上的事件被触发后,该事件不会向父节点传递。
类型 触发条件 最低版本
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 设备,重按时会触发 基础库 1.9.90 开始支持,低版本需做兼容处理

事件绑定的写法同组件的属性,以 key、value 的形式。

bind事件绑定不会阻止冒泡事件向上冒泡,catch事件绑定可以阻止冒泡事件向上冒泡。

自基础库版本 1.5.0 起,触摸类事件支持捕获阶段。捕获阶段位于冒泡阶段之前,且在捕获阶段中,事件到达节点的顺序与冒泡阶段恰好相反。需要在捕获阶段监听事件时,可以采用capture-bind、capture-catch关键字,后者将中断捕获阶段和取消冒泡阶段。

事例:

在下面的代码中,点击 inner view 会先后调用handleTap2、handleTap4、handleTap3、handleTap1。

<view class="container">
    <view bind:touchstart="handleTap1" capturebind:touchstart="handleTap2">
        outer view
        <view bind:touchstart="handleTap3" capture-bind:touchstart="handleTap4">inner view</view>    
    </view>
</view>

使用场景

一. 多个按钮点击,获取当前点击的是哪一个按钮

<view class="container">
    <block wx:for="{{5}}" wx:key="{{index}}">
        <view data-index="{{index}}" bindtap='clickTap'>
            <text style="color:{{currentIndex===index ? 'red' : 'blue'}}">{{'按钮' + index}}</text>
        </view>
    </block>
</view>
data: {
    currentIndex: 0
},
clickTap(event) {
    this.setData({
        currentIndex: event.currentTarget.dataset.index
    })
},

二. 监听动画结束

<view class="container">
    <view class='box'>
        <view style='width:50px;height:50px;background-color:red;' animation="{{animationAction}}" bindtap='clickTap' bindtransitionend="transitionend">
        </view>
    </view>
</view>
clickTap(event) {
    let animationAction = wx.createAnimation({
            duration: 1000,
            timingFunction: 'linear'
        });
    animationAction.scale(5).step();
    this.setData({
        animationAction: animationAction.export()
    })
},
transitionend(event) {
    console.log('动画结束' + event);
    let animationAction = wx.createAnimation({
            duration: 1000,
            timingFunction: 'linear'
        });
        animationAction.scale(1).step();
        this.setData({
            animationAction: animationAction.export()
        })
},
image.png

返回目录

上一篇下一篇

猜你喜欢

热点阅读