<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div {
position: absolute;
left: 0;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div></div>
<script>
var div = document.querySelector('div');
div.style.left = div.offsetLeft + 1 + 'px';
var timer = setInterval(function () {
if (div.offsetLeft >= 400) {
clearInterval(timer);
}
div.style.left = div.offsetLeft + 1 + 'px';
}, 3)
</script>
</body>
</html>
封装到函数中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div {
position: absolute;
left: 0;
width: 100px;
height: 100px;
background-color: pink;
}
span {
position: absolute;
left: 0;
top: 200px;
display: block;
width: 150px;
height: 150px;
background-color: purple;
}
</style>
</head>
<body>
<div></div>
<span>高瑶</span>
<script>
function animate(obj, target) {
var timer = setInterval(function () {
if (obj.offsetLeft >= target) {
clearInterval(timer);
}
obj.style.left = obj.offsetLeft + 5 + 'px';
}, 30);
}
var div = document.querySelector('div');
var span = document.querySelector('span');
animate(div, 300);
animate(span, 200);
</script>
</body>
</html>
优化函数后
function animate(obj, target) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
if (obj.offsetLeft >= target) {
//停止
clearInterval(obj.timer);
}
obj.style.left = obj.offsetLeft + 5 + 'px';
}, 30);
}