缓动动画添加回调函数
Tutorial: DOM实战
Category: JS
Published: 2026-04-07 13:58:26
Views: 20
Likes: 0
Comments: 0
<!DOCTYPE html>
<html lang="en">
<head>
<style>
span {
position: absolute;
left: 0;
top: 200px;
display: block;
width: 150px;
height: 150px;
background-color: purple;
}
</style>
</head>
<body>
<button class="btn500">点击夏雨荷到500</button>
<button class="btn800">点击夏雨荷到800</button>
<span>夏雨荷</span>
<script>
function animate(obj, target, callback) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var step = (target - obj.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if (obj.offsetLeft == target) {
clearInterval(obj.timer);
if (callback) {
callback();
}
}
obj.style.left = obj.offsetLeft + step + "px";
}, 15);
}
var span = document.querySelector("span");
var btn500 = document.querySelector(".btn500");
var btn800 = document.querySelector(".btn800");
btn500.addEventListener("click", function () {
animate(span, 500);
});
btn800.addEventListener("click", function () {
animate(span, 800, function () {
span.style.backgroundColor = "red";
});
});
</script>
</body>
</html>