JavaScript案例:按下键盘移动div

代码

css样式

<style>
    #t{
        position:absolute;
        width: 5px;
        height: 5px;
        background-color: red;
    }
</style>

html

注意:top、left样式必须写在标签的 style 属性中,JavaScript代码才能获取到属性

<div id="t" style="top: 50px;left: 50px;"></div>

js

<script>
    document.onkeydown = function(e){
        // console.log(e.keyCode)
        var t = document.getElementById("t")
        // top、left样式必须写在标签的style属性中,才能获取到
        var x = t.style.left
        var y = t.style.top
        x = parseInt(x)
        y = parseInt(y)
        // console.log(t)
        // console.log(x)
        // console.log(y)
        switch(e.keyCode){
            case 37:
                x = x - 5
                break;
            case 38:
                y = y - 5
                break;
            case 39:
                x = x + 5
                break;
            case 40:
                y = y + 5
                break;
        }
        t.style.left = x+"px"
        t.style.top = y+"px"
    }
</script>

原文出处:/show_1IX3mt8FXF6C.html