分为两种情况:
一、同时给某个元素绑定触摸事件和点击事件
使用 preventDefault 阻止元素默认事件来解决,在触摸事件中添加 e.preventDefault()就可以阻止click事件触发。
二、给两个元素分别绑定触摸和点击事件
思路:通过设置变量,判断是否触摸触摸状态,触摸状态下,不能触发点击事件
触摸事件代码:
var isTouching=false // 默认--不处于触摸状态
function touchTables() {
......
//绑定touchstart事件
moveTable.addEventListener("touchstart", touchStart, false);
function touchStart(e) {
......
}
//绑定touchmove事件
moveTable.addEventListener("touchmove", touchMove, false);
function touchMove(e) {
......
isTouching=true // 将状态设置为 触摸中
}
//监听触摸结束
moveTable.addEventListener("touchend",function(){
isTouching=false // 设置触摸状态为 没触摸
document.body.removeEventListener('touchmove', bodyScroll, false);
});
function bodyScroll(e) {
e.preventDefault();
}
}
点击事件代码:
//点击事件
btnList[i].button.onPointerUpObservable.add(function () {
// 不处于触摸状态下才执行
if (!isTouching) { // 判断是否触摸中
......
}
})
以上就是全部的逻辑,最后记录一下写的代码:
// 触摸
function touchTables() {
var moveTable = canvas //item_ID
var $win = document.window;
var tableWidth = moveTable.offsetWidth;
var halfWidth = tableWidth / 2;
var objTouches = null;
var startx, starty, tableLeft, distx = 0, disty = 0;
//绑定touchstart事件
moveTable.addEventListener("touchstart", touchStart, false);
function touchStart(e) {
objTouches = e.changedTouches[0];
tableLeft = parseInt(moveTable.style.left)
startx = parseInt(objTouches.pageX);
starty = parseInt(objTouches.pageY);
}
//绑定touchmove事件
moveTable.addEventListener("touchmove", touchMove, false);
function touchMove(e) {
objTouches = e.changedTouches[0];
distx = parseInt(objTouches.pageX) - startx;
disty = parseInt(objTouches.pageY) - starty;
//判断touch滑动的方向
if (disty > 10) {
isTouching=true
document.body.removeEventListener('touchmove', bodyScroll, false);
// 滑动时滚动条滚动
panel1ScrollView.verticalBar.value -= 0.015;
} else if (disty < 10 ) {
isTouching=true
document.body.removeEventListener('touchmove', bodyScroll, false);
// 滑动时滚动条滚动的多少
panel1ScrollView.verticalBar.value += 0.015;
}
else if (distx > 0 || distx < 0) {
isTouching=true
document.body.addEventListener('touchmove', bodyScroll, false); //向上向下滑动时取消body的滚动条事件
moveTable.style.left = ((tableLeft + distx < -halfWidth) ? -halfWidth : (tableLeft + distx > 0) ? 0 : tableLeft + distx) + "px";
}
}
moveTable.addEventListener("touchend",function(){
isTouching=false
document.body.removeEventListener('touchmove', bodyScroll, false);
});
function bodyScroll(e) {
e.preventDefault();
}
}
// 点击
btnList[i].button.onPointerUpObservable.add(function () {
// // 点击完成后去除面板
if (!isTouching) { // 判断是否触摸中
// 下层点击事件的代码
// 第一张图为0
clicks = i
switchImg()
// 隐藏蒙版
listMask.isVisible = !listMask.isVisible;
// 点击完成后去除面板
panel1ScrollView.isVisible = false;
}
})