缓动动画

2016-12-22  本文已影响0人  嘿喵heyMeow
效果图
缓动动画.gif
布局
<body>
<button id="btn">开始动画</button>
<div id="box" class="box"></div>
</body>
样式
<style>
        .box{
            width: 50px;
            height: 50px;
            background-color: skyblue;
            margin-top: 30px;
        }
</style>
JS
<script>
        window.onload = function(){
            var btn = document.getElementById('btn');
            var box = document.getElementById('box');
            var timer;
            var num = 0;
            var target =200;
            btn.onclick = function(){
                clearInterval(timer);
                setInterval(function(){
                    num ++;
                   //让左边距每次增大的距离越来越小,造成越来越慢的效果
                    num += (target-num)*0.2; 
                    if(Math.round(num)>=target){
                        num = target;
                        clearInterval()
                    }//Math.round()是数学函数:四舍五入
                    box.style.marginLeft = num +'px';
                },100);
            }
        }
</script>
上一篇 下一篇

猜你喜欢

热点阅读