<!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: rgb(27, 240, 240);
display: block;
text-align: center;
line-height: 150px;
color: palevioletred;
font-size: 15px;
position: absolute;
left: 0;
top: 200px;
}
</style>
</head>
<body>
<button>点击尘尘</button>
<div>
</div>
<span>尘尘</span>
</body>
<script>
// 简单动画函数封装ojb目标对象 target 目标位置
// 给不同的元素指定不同的定时器
function animate(obj, target) {
// 如果不断点击按钮,会连续开启定时器
// 只给元素设置一个定时器就好
clearInterval(obj.timer);
obj.timer = setInterval(function () {
if (obj.offsetLeft >= target) {
// 停止动画 本质是停止定时器
clearInterval(obj.timer);
}
obj.style.left = obj.offsetLeft + 1 + 'px';
}, 30);
}
var div = document.querySelector('div');
var span = document.querySelector('span');
var but = document.querySelector('button');
// 调用函数
animate(div, 500);
but.addEventListener('click',function(){
animate(span, 200)
})
</script>
</html>