![](https://img2020.cnblogs.com/blog/1968139/202006/1968139-20200606105845230-811117231.png)
<style>
* {
padding: 0;
margin: 0;
}
div {
position: absolute;
top: 20px;
left: 200px;
height: 80px;
80px;
background-color: pink;
}
</style>
<script>
window.addEventListener('load', function () {
var div = document.querySelector('div');
var Left = div.offsetLeft;
var x = 0;
// 添加定时器
var time = setInterval(fn, 500);
function fn() {
// 设置停止定时器事件
if (x == 6) {
// 移除定时器
clearInterval(time);
}
// 定时器触发效果
else {
Left += 80;
div.style.left = Left + 'px';
x++;
div.innerText = x;
}
}
})
</script>
<div class='div1'>
</div>
简单的动画函数封装
// 简单的动画函数封装
function animation(obj, target) {
// obj调用元素,target移动距离
obj.timer = setInterval(function () {
// 当元素offsetLeft等于移动距离时,计时器停止
if (obj.offsetLeft == target) {
clearInterval( obj.timer);
}
// 计时器每次执行时 元素的定位left增加5px
else {
obj.style.left = obj.offsetLeft + 5 + 'px';
}
}, 50);
}
var div = document.querySelector('.div1');
animation(div, 300);
var span = document.querySelector('span');
animation(span, 600)