javascript - 用光标键左右移动div

标签 javascript html cursor key

我正在尝试使用左侧位置移动 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";

FIDDLE

我会将我的昵称更改为“EagleEyes”

关于javascript - 用光标键左右移动div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22884236/

相关文章:

javascript - 如何将加载的音频设置为 HTML 音频标签 Controller ?

oracle - 存储过程: Cursor is bad?

javascript - 多种出版物和订阅

javascript - 对数 slider

html - 2 个跨度之间的间距不符合

html - HTML 和 CSS 中的图像 slider

qt - 如何在 QLineEdit 中设置插入符号闪烁光标的颜色

自定义 ArrayList Adapter 和 Cursor 的 Android 怪异行为

javascript - 如何判断文本框在C#中是否仅包含空格?

javascript - 如何引用同级属性以在属性名称声明中使用? [对象字面量、Javascript、es6]