[英]moving div with cursor keys left and right
I'm trying to move a div element using left position. 我正在尝试使用左侧位置移动div元素。 To do this i squared a div and got his element id in javascript to give it +-3pixels depending on ley strokes left and right.
为此,我对div求平方,并在javascript中获取其元素ID,以使其+ -3pixels取决于左右笔触。 I've added console logs to know this stuff is working and everything is flowing accordingly, the only problem is ... IT ISNT working !!!
我已经添加了控制台日志,以了解这些东西正在工作,并且一切都在相应地进行,唯一的问题是...它正在工作! I don't need a new code, just to understand what i'm doing wrong
我不需要新的代码,只是为了了解我在做什么错
The html: 的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>
the javascript file: 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.