如何将W键绑定(bind)到网页上的按钮
我尝试使用 .keypress 但它似乎不起作用。
这里是代码:
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<div class="d-pad">
<div id="d-up" class="button d up"></div>
<div id="d-right" class="button d right"></div>
<div id="d-down" class="button d down"></div>
<div id="d-left" class="button d left"></div>
</div>
<script>
$(document).keypress(function(e){ // keybiding
if (e.which == 87){
$("#d-up").click(function(){alert('UP')});
}
});
</script>
</body>
</html>
我尝试将 W 键与 id = d-up 的向上按钮绑定(bind),每当按下 W 时,都会出现一条警告,提示“向上”。这似乎不起作用。我在这里做错了什么吗?
谢谢
最佳答案
你没有说:
whenever W is pressed, show an alert
你说:
whenever W is pressed, set things up so that if a div with no content in it is clicked with the mouse, show an alert
摆脱点击处理程序。
$(document).keypress(function(e){
if (e.key == 87){
document.body.style.backgroundColor = "black";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
此演示中的注意事项:
- 您需要聚焦结果才能看到效果
- 我已改用背景颜色,因为
alert
已沙箱化在 stackoverflow 代码片段中 - w 与 W 不同
关于javascript - Html 上的键绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33403597/