js键盘按下移动元素

时间:2022-07-06 18:36:29

文章地址  https://www.cnblogs.com/sandraryan/

功能: 点击上下左右按钮,移动元素

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    .box {
        width: 100px;
        height: 100px;
        background-color: lightblue;
        position: fixed;
        top: 0;
        left: 0;
    }
    </style>
</head>
<body>
    <div class="box"></div>
    <script>
    var box = document.querySelector(‘.box‘);
    // 文档绑定点击时间
    document.onkeydown = function(ev){
        var e = ev || event;
        // 获取当前元素的左,上位置
        var l = box.offsetLeft;
        var t = box.offsetTop;
        // 比较按下的键的键码,是上下左右就像上下左右移动
        // (会移出页面,可以加父元素控制移动范围,或在js中判断超过某一值停止移动)
        switch(e.keyCode){
            case 37:
            l -= 5;
            break;
            case 38:
            t -=5;
            break;
            case 39:
            l  = 5;
            break;
            case 40:
            t  =5;
        }
        // 重新设置top left
        box.style.left = l   ‘px‘;
        box.style.top = t   ‘px‘;
    }
    </script>
</body>
</html>