我正在尝试使用左侧位置移动div元素。要做到这一点,我平方div,并在javascript中得到他的元素id给它+ -3像素,取决于左右的ley笔画。我添加了控制台日志,知道这些东西正在运行,一切都在流动,唯一的问题是...... IT ISNT正在工作!我不需要新代码,只是为了理解我做错了什么
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;
答案 0 :(得分:1)
你的空间太多,请替换
theMan.style.left = xLeft + " px";
// ^^ no space here
与
theMan.style.left = xLeft + "px";
我将把我的昵称改为&#34; EagleEyes&#34;