其他分享
首页 > 其他分享> > div跟随键盘移动

div跟随键盘移动

作者:互联网

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #div{
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: darkred;
            left: 100px;
        }
    </style>
</head>
<body>
    <div id="div"></div>
</body>
<script>
    var div = document.getElementById('div')
    console.log(getComputedStyle(div,null)['left'])  //凡是js中没有定义的元素都需要转成字符串传递参数
    document.onkeydown = function (event) {
        event = event || window.event
        console.log(event.keyCode)
        if(event.keyCode == 39){
            div.style.left = 10 + parseInt(getComputedStyle(div,null)['left']) + 'px'
        }
        else if(event.keyCode == 37){
            div.style.left = -10 + parseInt(getComputedStyle(div,null)['left']) + 'px'
        }
        else if(event.keyCode == 40){
            div.style.top = 10 + parseInt(getComputedStyle(div,null)['top']) + 'px'
        }
        else if(event.keyCode == 38){
            div.style.top = -10 + parseInt(getComputedStyle(div,null)['top']) + 'px'
        }
   }
    
</script>
</html>

标签:跟随,getComputedStyle,keyCode,键盘,div,null,event,left
来源: https://blog.csdn.net/TomKing9/article/details/116750325