微信小程序点击、双击、长按事件可参考 https://blog.csdn.net/qq_40477864/article/details/89159381
一、滑动事件
微信小程序的滑动事件是通过bindtouchmove实现的,通过比较滑动事件前后的坐标判断滑动方向,这里只给出了简单的左右滑动。
wxml:
<!--index.wxml-->
<view class="container">
<button bindtouchmove="move">
{{text}}
</button>
</view>
js:
//index.js
Page({
data: {
lastX: 0, //滑动开始时x坐标初始为0
lastY: 0, //滑动开始时y坐标初始为0
text: "没有滑动"
},
//滑动移动事件
move: function (e) {
//获取当前鼠标坐标
var currentX = e.touches[0].pageX
var currentY = e.touches[0].pageY
var text = ""
//左右方向滑动
if (currentX > this.data.lastX) {
text = "向右滑动"
}
else {
text = "向左滑动"
}
//将当前坐标进行保存以进行下一次计算
this.data.lastX = currentX
this.data.lastY = currentY
this.setData({
text: text,
});
},
})
二、事件冒泡
当一个组件拥有多个事件的时候,为了控制触发具体哪个或哪些事件,就需要控制事件冒泡。
我们先来看一个例子:
html:
<!--index.wxml-->
<view class="container">
<!-- 打印红色 -->
<view class="red" bindtap='printRed'>
<!-- 打印蓝色 -->
<view class="blue" bindtap='printBlue'>
<!-- 打印黄色 -->
<view class="yellow" bindtap='printYellow'></view>
</view>
</view>
</view>
js:
//index.js
Page({
data: {
},
printRed:function(){
console.log("red")
},
printBlue:function(){
console.log("blue")
},
printYellow:function(){
console.log("yellow")
}
})
图示:
当我们点击黄色控制台会打印如下图所示情况
有时候我们点击黄色并不希望触发蓝色和红色事件,这该怎么办呢?
这时我们可以借助catchtap来阻止事件冒泡,如下:
wxml:
<!--index.wxml-->
<view class="container">
<!-- 打印红色 -->
<view class="red" bindtap='printRed'>
<!-- 打印蓝色 -->
<view class="blue" bindtap='printBlue'>
<!-- 打印黄色 -->
<view class="yellow" catchtap='printYellow'></view>
</view>
</view>
</view>
此时我们点击黄色就只会触发黄色事件
这样做很好的阻止了蓝色和红色事件,那么问题来了,如果我想点击黄色不仅触发黄色事件还要触发红色事件怎么办呢?