JavaScript基础教程

js的简单运动

2018-07-11  本文已影响0人  StevenTang
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>方块运动</title>
</head>
    <style>
    *{
        padding: 0;
        margin: 0;
        list-style: none;
    }
        div{
            position: absolute;
            left: 600px;
            top:0;
            width: 100px;
            height: 100px;
            background: orange;
        }
        span{
            position: absolute;
            left: 300px;
            top:0;
            width:1px;
            height: 100px;
            background: #000;
        }
    </style>
<body>
    <div></div>
    <span></span>
</body>
<script>
    var div = document.getElementsByTagName('div')[0];
    var timer = null;
    div.onclick = function () {
        startMove(this);
    }
    function startMove (obj) {
        clearInterval(timer);
        var iSpeed;
        if (obj.offsetLeft > 300) {
            iSpeed = -5;
        } else {
            iSpeed = 5
        }
        timer = setInterval(function (){
            if (Math.abs(300 - obj.offsetLeft) < Math.abs(iSpeed)) {
                clearInterval(timer);
                obj.style.left = '300px'
            } else {
                obj.style.left = obj.offsetLeft + iSpeed + 'px';
            }
        },30)
    }
</script>
</html>
上一篇 下一篇

猜你喜欢

热点阅读