微信小程序的事件冒泡和捕获

本文详细介绍了微信小程序中事件的冒泡、捕获机制以及如何阻止事件冒泡和中断事件捕获。通过示例代码展示了不同事件绑定方式下,事件从子组件向父组件传递的过程,并解释了catch和capture-bind事件修饰符的用法。
摘要由CSDN通过智能技术生成

微信小程序的事件冒泡和捕获

事件冒泡

当一个组件上的事件被触发后,该事件会向父节点传递。

bind事件名

eventBind.wxss

.one{
    width: 300px;
    height: 300px;
    background: #96c24e;
}
.two{
    width: 200px;
    height: 200px;
    background-color: #bec936;
}
.three{
    width: 100px;
    height: 100px;
    background-color: #f97d1c;
}

eventBind.js

Page({
	_handlerOne:function(){
        console.log("one");
    },
    _handlerTwo:function(){
        console.log("Two");
    },
    _handlerThree:function(){
        console.log("Three");
    }
})

eventBind.wxml

<text>事件的冒泡</text>
<view class="one" bindtap="_handlerOne">one
    <view class="two" bindtap="_handlerTwo">two
        <view class="three" bindtap="_handlerThree">three</view>
    </view>
</view>

当点击three层时:

在这里插入图片描述

事件会冒泡到two层和one层:

在这里插入图片描述

阻止事件冒泡

catch事件名

eventBind.wxml

<text>事件的冒泡</text>
<view class="one" bindtap="_handlerOne">one
    <view class="two" catchtap="_handlerTwo">two
        <view class="three" bindtap="_handlerThree">three</view>
    </view>
</view>

当点击three层时:

在这里插入图片描述

事件向父组件冒泡,冒泡到two层时被阻止。
在这里插入图片描述

事件捕获

捕获阶段位于冒泡阶段之前,且在捕获阶段中,事件到达节点的顺序与冒泡阶段恰好相反。需要在捕获阶段监听事件时,可以采用:

capture-bind:事件名

eventBind.wxml

<view class="one" capture-bind:tap="_handlerOne">one
    <view class="two" capture-bind:tap="_handlerTwo">two
        <view class="three" capture-bind:tap="_handlerThree">three</view>
    </view>
</view>

当点击three层时:

在这里插入图片描述

事件捕获开始,从被点击的父组件执行到该被点击的元素:

在这里插入图片描述

中断事件捕获

capture-catch:事件名

capture-catch关键字,后者将中断捕获阶段和取消冒泡阶段。

eventBind.wxml

<view class="one" capture-bind:tap="_handlerOne">one
    <view class="two" capture-catch:tap="_handlerTwo">two
        <view class="three" capture-bind:tap="_handlerThree">three</view>
    </view>
</view>

当点击three层:

在这里插入图片描述
事件在two层被中断:
在这里插入图片描述

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值