<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
position: absolute;
left: 0;
top: 30px;
width: 100px;
height: 100px;
background-color: pink;
}
span {
position: absolute;
left: 0;
top: 200px;
display: block;
width: 300px;
height: 300px;
background-color: purple;
}
</style>
</head>
<body>
<div></div>
<span></span>
<button>向前走500px</button>
<button>向前走800px</button>
<script>
function animate(obj, target, callback) { //回调函数,在走到800px后变色
clearInterval(obj.timer); //避免不停点击按钮,开启新的定时器,大盒子一直走,所以需要在开启定时器前清除上一个定时器
obj.timer = setInterval(function () {
//取整是为了避免产生小数到不了target
var step = (target - obj.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
obj.style.left = obj.offsetLeft + step + 'px';
if (obj.offsetLeft == target) {
clearInterval(obj.timer);
if(callback) {
callback();
}
}
}, 30)
}
var div = document.querySelector('div');
var span = document.querySelector('span');
var btn = document.querySelector('button');
var btn2 = btn.nextElementSibling;
animate(div, 200);
btn.addEventListener('click', function () {
animate(span, 500);
})
btn2.addEventListener('click', function () {
animate(span, 800, function() {
span.style.backgroundColor = 'red';
});
})
</script>
</body>
</html>
定时器做动画效果
于 2022-06-17 17:19:30 首次发布