<!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 {
width: 100px;
height: 100px;
background-color: orchid;
position: absolute;
left: 0;
}
span{
width: 150px;
height: 150px;
background-color: paleturquoise;
display: block;
position: absolute;
left: 0;
top: 200px;
}
</style>
</head>
<body>
<div>
</div>
<span></span>
</body>
<script>
// 简单动画函数封装ojb目标对象 target 目标位置
function animate(ojb, target) {
var timer = setInterval(function () {
if (ojb.offsetLeft >= target) {
// 停止动画 本质是停止定时器
clearInterval(timer);
}
ojb.style.left = ojb.offsetLeft + 1 + 'px';
}, 30);
}
var div = document.querySelector('div');
var span = document.querySelector('span');
// 调用函数
animate(div, 500);
animate(span, 200);
</script>
</html>