缓动动画原理
4.4 缓动效果原理

<button>点击夏雨荷才走</button>
<span>夏雨荷</span>
<script>
// 缓动动画函数封装obj目标对象 target 目标位置
function animate(obj, target) {
// 先清除以前的定时器,只保留当前的一个定时器执行 每次点击按钮执行时 都先清除上次的定时器 否则会加快运作
clearInterval(obj.timer);
obj.timer = setInterval(function() {
// 步长值写到定时器的里面
var step = (target - obj.offsetLeft) / 10;
if (obj.offsetLeft == target) {
// 停止动画 本质是停止定时器
clearInterval(obj.timer);
}
// 把固定值改为递减值 step
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);
})
匀速动画 就是 盒子是当前的位置 + 固定的值 10
缓动动画 就是 盒子当前的位置 + 变化的值
(目标值 - 现在的位置) / 10)
var step = (target - obj.offsetLeft) / 10;
4.5 动画函数多个目标值之间移动

obj.timer = setInterval(function() {
var step = (target - obj.offsetLeft) / 10;
此处有bug: 当步长值>0时 盒子并没有走到500 就停下; 当盒子从800往500走时 步长值<0 盒子也没有走到500
此时应该 给步长值取整数 当步长值>0时 取大的整数; 当步长值<0时 取小数整数。
step = step > 0 ? Math.ceil(step) : Math.floor(step);
4.6 动画函数添加回调函数
回调函数原理:函数可以作为一个参数。将这个函数作为参数传到另一个函数里面,当那个函数执行完之后,在执行传进去的这个函数,这个过程就叫做回调。
回调函数写的位置:定时器结束的位置。
if (obj.offsetLeft == target) {
clearInterval(timer);
// 回调函数写到定时器结束里面
if (callback) {
// 调用函数
callback();
}
}
btn800.addEventListener('click', function() {
animate(span, 800, function() {
// 当盒子走到800时 程序完毕时 再调用函数
// alert('你好吗');
span.style.backgroundColor = 'red';
});
})
4.7 引用animate动画函数
首先先把 js 封装到文件,需要时候引用。
当我们鼠标经过 sliderbar 就会让 con这个盒子滑动到左侧
当我们鼠标离开 sliderbar 就会让 con这个盒子滑动到右侧
sliderbar.addEventListener('mouseenter', function() {
//mouseenter 和 mouseover 的区别 mouseenter不会冒泡
// animate(obj, target, callback);
animate(con, -160, function() {
// 当我们动画执行完毕,就把 ← 改为 → 此时需要调用 回调函数
sliderbar.children[0].innerHTML = '→';
});
})
sliderbar.addEventListener('mouseleave', function() {
// animate(obj, target, callback);
animate(con, 0, function() {
sliderbar.children[0].innerHTML = '←';
});
})
1200

被折叠的 条评论
为什么被折叠?



