尝试在单击/触摸时将数字增加 1,在按住时增加许多。这是用鼠标工作的(似乎有点问题)。但是我怎样才能让它与使用“触摸”事件的触摸设备一起工作呢?
我想像下面那样做,因为我有很多按钮做同样的工作。也请使用纯 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")
它将起作用。至少,它对我有用。 |
是一个 bitwise operator当像您使用它一样使用时,一切都会出现未定义的行为。
编辑:我认为 mousedown
事件有效,因为首先评估条件 event == "mousedown"
,结果为真。最后,我们有,true | “点击” | “touchstart”
也返回 true。
然而,对于click和touchstart,第一次比较返回false,而false | “点击” | “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")
关于javascript - 相当于 mousedown 的 JS 触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53030380/