WX小程序捕、获冒泡事件(阻止冒泡)

mac2025-10-08  1

文章参考

wx小程序 事件

语法说明

key以bind或者catch开头,然后跟上事件的类型,如bindtap、catchtouchstart。自基础库版本1.5.0起,bind和catch后可以紧跟一个冒号,其含义不变,如bind:tap、catch:touchstart。同时bind和catch前还可以加上capture-来表示捕获阶段。value是一个字符串,需要在对应的页面Page构造器中定义同名的函数,否则触发事件时在控制台会有报错信息。bind和capture-bind的含义分别代表事件的冒泡阶段和捕获阶段

案例说明

capture-bind & bind 先捕获事件再冒泡事件

<view id="outer" bind:touchstart="outerBubble" capture-bind:touchstart="outerCapture"> outer view <view id="inner" bind:touchstart="innerBubble" capture-bind:touchstart="innerCaputure"> inner view </view> </view> Page({ outerCapture: function () { console.log("outerCapture"); }, outerBubble: function () { console.log("outerBubble"); }, innerCaputure: function () { console.log("innerCaputure"); }, innerBubble: function () { console.log("innerBubble"); } })

触发外部控件

结果:outerCapture outerBubble

先触发捕获事件,再触发冒泡事件

触发内部控件

结果:outerCapture innerCaputure innerBubble outerBubble

先触发捕获事件,再触发冒泡事件

catch-bind & bind 触发当前控件的事件,阻止捕获事件和冒泡事件

bind事件绑定不会阻止冒泡事件向上冒泡,catch事件绑定可以阻止冒泡事件向上冒泡。 如果将上面代码中的第一个capture-bind改为capture-catch,将只触发handleTap2(capture-catch将中断捕获阶段和取消冒泡阶段)

<view bindtap="topBubble" capture-bind:tap="topCapture"> 祖先节点 <view id="outer" catch:touchstart="outerBubble" capture-bind:touchstart="outerCapture"> 如果将上面代码中的第一个capture-bind改为capture-catch,将只触发handleTap2(capture-catch将中断捕获阶段和取消冒泡阶段) <view id="inner" bind:touchstart="innerBubble" capture-bind:touchstart="innerCaputure"> inner view </view> </view> </view> Page({ topBubble: function () { console.log("topBubble"); }, topCapture: function () { console.log("topCapture"); }, outerCapture: function () { console.log("outerCapture"); }, outerBubble: function () { console.log("outerBubble"); }, innerCaputure: function () { console.log("innerCaputure"); }, innerBubble: function () { console.log("innerBubble"); } })

触发顶部控件

结果:topCapture topBubble

先触发捕获事件,再触发冒泡事件

触发中间控件

结果:outerCapture outerBubble

catch:touchstart 阻止事件冒泡

触发内部控件

结果:outerCapture innerCaputure innerBubble outerBubble

先触发捕获事件,再触发冒泡事件

最新回复(0)