javascript - 使用键盘箭头向上和向下移动 div
问题描述
我希望能够cube
使用键盘箭头移动带有 id 的 div。左右移动正常工作,但我不能让它上下移动。
var output=document.getElementById("output");
var cube=document.getElementById("cube");
var left=0;
var top=0;
document.addEventListener("keydown", function(e) {
output.innerHTML='Key code: ' + e.which + '<br />' + 'Key Name: ' + e.key;
var key=e.which;
switch (key) {
case 38: //arrow up
top = top - 10;
cube.style.top= top + "px";
cube.style.background="green";
break;
case 40: //arrow down
top = top + 10;
cube.style.top= top + "px";
cube.style.background="#14B4AA";
break;
case 39: //arrow right
left = left + 10;
cube.style.left= left + "px";
cube.style.background="blue";
break;
case 37: //arrow left
left = left - 10;
cube.style.left= left + "px";
cube.style.background="brown";
break;
}
});
...
解决方案
你不能有一个名为“top”的全局变量。
top 是一个宿主对象,它指向最外层的窗口对象,在框架内使用时最有用 https://humanwhocodes.com/blog/2007/06/03/javascript-variable-names-you-shouldn-t -利用/
如果变量名称被更改,或者如果它的范围不是窗口(例如在事件侦听器内),您的代码可以正常工作。
var output=document.getElementById("output");
var cube=document.getElementById("cube");
var left=0;
var t=0;
document.addEventListener("keydown", function(e) {
output.innerHTML='Key code: ' + e.which + '<br />' + 'Key Name: ' + e.key;
var key=e.which;
e.preventDefault(); // used to prevent window scroll on up/down keys
switch (key) {
case 38: //arrow up
t = t - 10;
cube.style.top= t + "px";
cube.style.background="green";
break;
case 40: //arrow down
t = t + 10;
cube.style.top= t + "px";
cube.style.background="#14B4AA";
break;
case 39: //arrow right
left = left + 10;
cube.style.left= left + "px";
cube.style.background="blue";
break;
case 37: //arrow left
left = left - 10;
cube.style.left= left + "px";
cube.style.background="brown";
break;
}
});
#cube {position: absolute}
<div id="cube">CUBE</div>
<div id="output">OUTPUT</div>
推荐阅读
- java - 数据绑定错误:找不到符号导入 com.example.project_name.package_name
- javascript - 如何使用打字稿在我的角度组件中实现下面的 JavaScript 代码?
- airflow-scheduler - Timedeltasensor 从计划间隔延迟
- java - 我有一个用于 kafka 连接的 kafka 管道(json 问题更新)
- java - 无法使用 Morphia 2.0.2 检索现有文档
- c# - Microsoft Graph API 错误:MailboxNotEnabledForRestAPI
- javascript - Javascript / 验证输入
- sql-server - 使用 ORDER BY 的查询如何比没有排序的相同查询运行得更快?
- spring-boot - Git commit 可以立即运行,但在 intellij 中 gradle clean build 需要将近 5 分钟。重新同步在几秒钟内发生
- npm - npm 安装错误“无法读取未定义的属性‘最新’”