前端之家收集整理的这篇文章主要介绍了
JS轮播图中缓动函数的封装,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
轮播图的根本其实就是缓动函数的封装,如果说轮播图是一辆跑动的汽车,那么缓动函数就是它的发动机,今天本文章就带大家由简入繁,封装属于自己的缓动函数~~
我们从需求的角度开始,首先给出一个简单需求:
1、我想让页面中的一个盒子从开始的位置匀速向右运动到200px的地方,该怎么实现?
分析:
1)我们需要知道盒子在哪个地方,这个可以通过offsetLeft属性去获取;
2)要让盒子匀速运动,对于js肯定需要setInterval了;
3)要让盒子向右边跑起来?那就是需要不停改变盒子与左边起始点的距离,有margin-left,还有定位的left,这里我选择了改变绝对定位的left;
4)跑到离开始点200px的距离我们要停下来,使用clearInterval就可以了。
接下来直接上代码了
<div class="jb51code">
<pre class="brush:xhtml;">
<!DOCTYPE html>
<html lang="en">
Document
0 ? Math.ceil(step):Math.floor(step);// 这里如果将currentDistance定时器外面声明可以不用写,如果放在定时器内声明,因为offsetLeft取整的特性,要对step进行取整
if(Math.abs(currentDistance - target) > Math.abs(step)) {
currentDistance += step;
tag.style.left = currentDistance + 'px';
}else {
tag.style.left = target + 'px'
clearInterval(timer);
timer = null;
}
},17)
0 ? Math.ceil(step) : Math.floor(step);
currentDistance += step;
tag.style[k] = currentDistance / 100;
} else if (k == 'zIndex') {
tag.style[k] = obj[k];
else {
var currentDistance = parseInt(getStyle(tag,k)) || 0,target = obj[k],step = (target - currentDistance) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
currentDistance += step;
tag.style[k] = currentDistance + 'px';
}
if (target != currentDistance) {
flag = false // 只要还有
属性没有运动完成,就不会清楚定时器
}
}
if (flag) {
clearInterval(tag.timer)
fn && fn();// 所有定时器走完,这里执行回调
函数,短路操作避免不传回调
函数也不会报错。
}
},17)
}
获取样式的兼容
函数,上面的缓动
函数的依赖
function getStyle(tag,attr) {
if (tag.currentStyle) {
return tag.currentStyle[attr];
} else {
return getComputedStyle(tag,null)[attr];
}
}