效果图
结构
###
<button class="btn500">点击夏雨荷才走到500</button>
<button class="btn800">点击夏雨荷才走到800</button>
<div></div>
<span>夏雨荷</span>
CSS
div {
position: absolute;
left: 0;
width: 100px;
height: 100px;
background-color: pink;
}
span {
position: absolute;
left: 0;
top: 100px;
background-color: red;
width: 100px;
height: 100px;
}
js
var btn500 = document.querySelector('.btn500');
var btn800 = document.querySelector('.btn800');
// 简单动画函数封装obj目标对象 target 目标位置
// 给不同的元素指定了不同的定时器
function animate (obj, target, callback)
{
// console.log(callback); callback = function () { } 调用的时候callback()
// 当我们不断的点击按钮 这个元素的速度越来越快 因为开启了太多的定时器
// 解决方案 让给我们的元素只有一个定时器执行
// 先清除以前的定时器 只保留当前的一个定时器执行
clearInterval(obj.timer);
obj.timer = setInterval(function ()
{
// var step = Math.ceil((target - obj.offsetLeft) / 10);
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 div = document.querySelector('div');
var span = document.querySelector('span');
var btn = document.querySelector('button');
animate(div, 300);
btn500.addEventListener('click', function ()
{
animate(span, 500);
})
btn800.addEventListener('click', function ()
{
animate(span, 800, function ()
{
// alert('你好吗');
span.style.backgroundColor = 'pink';
});
})