我正在 Javascript Canvas 中制作一个简单的播放器 Action 。 (上下左右)
我在屏幕上为移动播放器创建了 4 个按钮。我对按钮使用了以下代码,因为我想移动播放器直到释放按钮。
upBtn.addEventListeter('mousedown',()=>{
let interval=setInterval(()=>{
player.y--;
}, 50);
upBtn.addEventListener('mouseup',()=>{
clearInterval(interval);
});
});
当在计算机中单击按钮时,上面的代码可以完美运行。但是在移动端它不起作用。我也尝试使用
touchdown
和 touchup
但它没有用。我应该对代码进行哪些更改才能使其在移动设备中也能正常工作?
提前致谢
最佳答案
您正在寻找 touchstart
和 touchend
function upFunc(event) {
//prevents some devices to emulate the click event
event.preventDefault();
let interval=setInterval(()=>{
player.y--;
}, 50);
upBtn.addEventListener('mouseup',downFunc);
upBtn.addEventListener('touchend',downFunc);
}
function downFunc(e) {
e.preventDefault();
clearInterval(interval);
}
upBtn.addEventListeter('mousedown', upFunc);
upBtn.addEventListeter('touchstart', upFunc);
请注意,要在 vanilla js 中同时支持鼠标和触摸,您必须添加两个事件监听器。此外,某些设备会模拟鼠标事件,因此您可以使用
preventDefault()
确保你的函数只触发一次。
关于javascript - 当mousedown直到mouseup时如何做工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69491293/