位置动画以及四个方向移动的动画




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
          width: 200px;
          height: 200px;
          background: red;
          position: absolute;
          left: 0;
          top: 30px;
        }
      </style>
</head>
<body>
    <button>开始运动</button>
    <div></div>
    <script>
        var div = document.querySelector('div')
        var button = document.querySelector('button')
        button.onclick = function (){
            var timer = setInterval(function(){
                // offsetLeft先获取,获取之后+5,然后再赋值给样式的left,不要忘了单位
                // offsetLeft是实时获取的,只要样式发生了变化,offsetLeft随之更新了
                div.style.left = div.offsetLeft + 10 + 'px'
                if(div.offsetLeft >= 500){
                    clearInterval(timer)
                  }  
            },30)
        }
    </script>
</body>
</html>


四个方向移动的动画


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 200px;
            height: 200px;
            background: red;
            position: absolute;
            left: 0;
            top: 30px;
        }
    </style>
</head>
<button id="you">向右</button>
<button id="zuo">向左</button>
<button id="shang">向上</button>
<button id="xia">向下</button>
<div></div>

<body>
    <script>
        var div = document.querySelector('div')
        document.querySelector('#you').onclick = function(){
            var timer1 = setInterval(function(){
                div.style.left = div.offsetLeft + 10 + 'px'
                if(div.offsetLeft >= 400){
                    clearInterval(timer1)
                }
            },30)
        }
        document.querySelector('#xia').onclick = function(){
            var timer2 = setInterval(function(){
                div.style.top = div.offsetTop + 10 + 'px'
                if(div.offsetTop >= 400){
                    clearInterval(timer2)
                }
            },30)
        }
        document.querySelector('#zuo').onclick = function(){
            var timer3 = setInterval(function(){
                div.style.left = div.offsetLeft - 10 + 'px'
                if(div.offsetLeft <= 0){
                    clearInterval(timer3)
                }
            },30)
        }
        document.querySelector('#shang').onclick = function(){
            var timer4 = setInterval(function(){
                div.style.top = div.offsetTop - 10 + 'px'
                if(div.offsetTop <= 40){
                    clearInterval(timer4)
                }
            },30)
        }
    </script>
</body>

</html>
发布了60 篇原创文章 · 获赞 3 · 访问量 524

猜你喜欢

转载自blog.csdn.net/dfc_dfc/article/details/105568550