js keyboard pressing elements move

Articles address https://www.cnblogs.com/sandraryan/

Function: Click the up and down buttons, move elements

<!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= document.querySelector Box ( 'Box.' );
     // document binding click time 
    document.onkeydown = function (EV) {
         var E = || EV Event;
         // Get the left of the current element, the position of 
        var L = Box .offsetLeft;
         var T = box.offsetTop;
         // comparing the key code key pressed, up and down movement is up and down as 
        // (move out of the page, you can be added to control the movement range of the parent element, or more than determined in the js a value stops moving) 
        Switch (e.keyCode) {
             Case 37 [ : 
            L - =. 5 ;
             BREAK ;
             Case 38 is : 
            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>

 

Guess you like

Origin www.cnblogs.com/sandraryan/p/11620772.html