元素移动动画

元素移动动画元素移动动画

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        .btn1{
            margin-top: 20px;
        }

        .btn2{
            margin-top: 20px;
        }

        .dv1{
            margin-top: 40px;
            width: 140px;
            height: 80px;
            background: pink;
            position: absolute;
            left: 10px;
        }
    </style>
</head>
<body>
    <input type="button" id="btn1" class="btn1" value="移动到400px">
    <input type="button" id="btn2" class="btn2" value="移动到800px">

    <div class="dv1" id="dv1"></div>

    <script>
        function my$(id){
            return document.getElementById(id)
        }

        my$('btn1').onclick = function () {
            animation(my$('dv1'), 400)
        }

        my$('btn2').onclick = function(){
            animation(my$('dv1'),800)
        }

//        动画函数
        function animation(element, target){
            clearInterval(element.tempTime)
            element.tempTime = setInterval(function(){
                var tempLeft = element.offsetLeft
                var flag = 10
                flag = tempLeft < target ? flag: -flag
                tempLeft += flag

                if(Math.abs(target - tempLeft) > flag){
                    element.style.left = tempLeft + 'px'
                }else{
                    clearInterval(tempTime)
                    element.style.left = target + 'px'
                }
            }, 20)
        }
    </script>
</body>
</html>

 

相关文章: