我正在尝试使用左侧位置移动 div 元素。为了做到这一点,我对一个 div 进行了平方,并在 javascript 中获取了他的元素 id,根据左侧和右侧的 ley 笔划给它 +-3 像素。我添加了控制台日志来知道这些东西正在工作并且一切都相应地进行,唯一的问题是......它不工作!我不需要新代码,只是为了了解我做错了什么
HTML:
<html>
<body>
<div id="container">
<div id="guy"> </div>
</div>
</body>
<script src="script.js"></script>
<style>
#container{background-color: teal;width: 500px;height: 500px;margin: auto; position: absolute;}
#guy{background-color: black;width: 30px;height: 30px;}
</style>
</html>
JavaScript 文件:
var theMan = document.getElementById('guy');
theMan.style.position = "absolute";
xLeft = 0;
function move(e) {
var e = e.keyCode;
switch(e) {
case 37:
if (xLeft == 0) {
console.log("Already reached the left edged");
} else {
console.log("Pressed LEFT");
xLeft -= 3;
moveGuy();
}
break;
case 39:
if (xLeft == 500) {
console.log("Already reached the right edged");
} else {
console.log("Pressed RIGHT");
xLeft += 3;
moveGuy();
console.log(xLeft);
}
break;
default:
console.log("Use the cursor keys idiot!");
break;
}
}
function moveGuy() {
theMan.style.left = xLeft + " px";
console.log("moving");
}
document.onkeydown = move;
最佳答案
您的空间过多,请更换
theMan.style.left = xLeft + " px";
// ^^ no space here
与
theMan.style.left = xLeft + "px";
我会将我的昵称更改为“EagleEyes”
关于javascript - 用光标键左右移动div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22884236/