前端学习(453):移动

给你一囗甜甜゛ 提交于 2020-01-20 16:39:02
<!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>
    div{width: 100px;height: 100px;background-color: orange;position:absolute;left: 400px;top: 400px;}
    </style>
</head>
<body>
   
    <button id="upBn">上</button>
    <button id="leftBn">左</button>
    <button id="downBn">下</button>
    <button id="rightBn">右</button>
    <div id="div0"></div>
    <script>
    
    
    var upBn=document.getElementById("upBn");
    var leftBn=document.getElementById("leftBn");
    var rightBn=document.getElementById("rightBn");
    var downBn=document.getElementById("downBn");
    var div=document.getElementById("div0");
    var speed=10;
    div.lefts=400;
    div.tops=400;
    upBn.addEventListener("click",clickHandle);
    leftBn.addEventListener("click",clickHandle);
    rightBn.addEventListener("click",clickHandle);
    downBn.addEventListener("click",clickHandle);
    function clickHandle(){
        switch(this){
            case upBn:
            div.tops-=speed;
            break;
            case downBn:
            div.tops+=speed;
            break;
            case leftBn:
            div.lefts-=speed;
            break;
            case rightBn:
            div.lefts+=speed;
            break;
        }
        div.style.left=div.lefts+"px";
        div.style.top=div.tops+"px";
    }
    </script>
</body>
</html>

运行结果

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!