效果图
缓动动画.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>
网友评论