缓动动画原理
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>点击夏雨荷才走</button>
<span>夏雨荷</span>
<script>
function animate(obj, target) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var step = (target - obj.offsetLeft) / 10;
if (obj.offsetLeft == target) {
clearInterval(obj.timer);
}
obj.style.left = obj.offsetLeft + step + "px";
}, 15);
}
var span = document.querySelector("span");
var btn = document.querySelector("button");
btn.addEventListener("click", function () {
animate(span, 500);
});
</script>
</body>
</html>