美文网首页
缓动动画

缓动动画

作者: 嘿喵heyMeow | 来源:发表于2016-12-22 20:22 被阅读0次
效果图
缓动动画.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>

相关文章

网友评论

      本文标题:缓动动画

      本文链接:https://www.haomeiwen.com/subject/huyhvttx.html