我有一个具有常规空格键功能的网站,而不仅仅是在输入框内,所以如果目标是正文,我就无法返回false。我只想阻止它向下滚动页面,但允许其他功能。是否可以使用vanilla JS来做到这一点?这是我的代码:
//Many other functions here
function spacebar() {
window.onkeydown = function(e) {
if ((watch.isOn) && (!done)) {//u can stop it with any key
watch.freeze();//stop the stopwatch
}
else if (e.keyCode == 32) {
if (done) {
watch.start();//start the stopwatch
stage = 1;
}
if (stage === 0) {
stage = 1;
}
}
}

<html>
<body>
<h1 id="timer">0:00.000</h1>
<script src="js/timer.js"></script>
<!--The JS starts and stops this timer.-->
</body>
</html>
&#13;
因此,当按下空格键时它会启动计时器,并在按下任何键时停止计时器。
答案 0 :(得分:2)
按空格键的默认行为是滚动。我们可以使用
来防止默认行为 event.preventDefault();
您正在使用window.onkeydown,将事件参数传递为var e。正如您所演示的,您知道如何通过键码识别键。现在,如果按下的键是空格键,则阻止默认行为(在这种情况下包括滚动)。您可以选择定义自己的行为。