我有简单的 JS 游戏脚本,但加速对象的唯一方法是按钮
<button onmousedown="accelerate(-0.1)" onmouseup="accelerate(0.1)">speed ++</button>
有功能:
function accelerate(n) {
test.gravity = n;
}
问题是如何将按钮单击更改为按键以加速? 基本上我不知道。
最佳答案
例如,您可以向 window.document 对象添加监听器
const test = {
gravity: 0.0
};
window.document.addEventListener('keyup', (e) => {
// arrow up
if (e.keyCode === 38) accelerate(0.1);
// arrow down
if (e.keyCode === 40) accelerate(-0.1);
console.log(test.gravity);
})
function accelerate (n) {
test.gravity = n;
}
关于javascript - 功能从按钮变为按键。 HTML5/JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47643535/