JS触摸事件相当于mousedown



点击/触摸时尝试增加一个数字,按住时尝试增加多个数字。这是用鼠标操作的(看起来有点bug(。但是如何使用"触摸"事件使其与触摸设备一起工作?

我想像下面这样做,因为我有很多按钮可以做同样的工作。也请使用纯JS。

window.addEventListener("load", function() {
var count = 0;
var iv = null;
["btn-1", "btn-2"].forEach(function(object) {
["click", "mousedown", "mouseup", "mouseleave", "touchstart"].forEach(function(event) {
document.getElementById(object).addEventListener(event, function() {
if (event == "mousedown" | "click" | "touchstart") {
iv = setInterval(function() {
if (object == "btn-1") {
count++;
} else {
count--;
}
document.getElementById("count").innerHTML = count;
}, 100);
} else {
clearInterval(iv);
}
});
});
});
});
#btn-1 {
width: 6em;
height: 6em;
}
#btn-2 {
position: relative;
top: -0.6em;
width: 6em;
height: 6em;
}
#count {
position: relative;
font-size: 4em;
top: 0.3em;
left: 1em;
}
<head>
</head>
<body>
<button id="btn-1">button up</button>
<button id="btn-2">button down</button>
<label id=count>0</label>
</body>

如果将条件更改为if (event == "mousedown" || event == "click" || event == "touchstart"),它将起作用。至少,它对我有效。|是一个按位运算符,当像你使用它一样使用时,一切都会变成未定义的行为。

编辑:我认为mousedown事件之所以有效,是因为首先评估条件event == "mousedown",结果为true。最后,我们得到了true | "click" | "touchstart",它也返回true。

但是,对于点击和触摸启动,第一个比较返回false,false | "click" | "touchstart"返回false,因此该条件永远不会执行。

希望这对你有所帮助。干杯

console.log("mousedown" | "click" | "touchstart")
event = "mousedown";
console.log(event == "mousedown" | "click" | "touchstart")
console.log(true | "click" | "touchstart")
event = "click";
console.log(event == "mousedown" | "click" | "touchstart")
event = "touchstart";
console.log(event == "mousedown" | "click" | "touchstart")

最新更新