1、封装的动画js:
var CustomAnimate = (function() {
function animate(element, properties, callback) {
var duration = properties.duration || 1000;
var easing = properties.easing || "linear";
var start = performance.now();
function update(time) {
var timeFraction = (time - start) / duration;
if (timeFraction > 1) timeFraction = 1;
var progress = CustomAnimate.easing[easing](timeFraction);
for (var property in properties) {
if (property !== "duration" && property !== "easing") {
var startValue = parseFloat(getComputedStyle(element)[property]);
var endValue = parseFloat(properties[property]);
var currentValue = startValue + progress * (endValue - startValue);
element.style[property] = currentValue + (property === "opacity" ? "" : "px");
}
}
if (timeFraction < 1) {
requestAnimationFrame(update);
} else {
if (callback) callback();
}
}
requestAnimationFrame(update);
}
// 缓动函数
function easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
}
return {
animate: animate,
easing: {
linear: function(t) {
return t;
},
easeInOutQuad: easeInOutQuad
}
};
})();
2、html示例页面及相关调用:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>轮播图</title>
<style>
* {
margin:0;
padding:0;
}
.box {
width:560px;
height:300px;
margin:100px auto;
overflow:hidden;
position:relative;
}
.rollImg {
width:3360px;
position:absolute;
top:0;
left:-560px;
}
.rollImg li {
width:560px;
height:300px;
list-style:none;
float:left;
}
</style>
</head>
<body>
<div class="box">
<!--图-->
<ul class="rollImg" id="rollImg">
<li><img src="images/4.jpg" alt=""></li>
<li><img src="images/1.jpg" alt=""></li>
<li><img src="images/2.jpg" alt=""></li>
<li><img src="images/3.jpg" alt=""></li>
<li><img src="images/4.jpg" alt=""></li>
<li><img src="images/1.jpg" alt=""></li>
</ul>
</div>
<script src="animation.js"></script>
<script>
var index = 1;
function animation(){
index++;
// 使用示例
var rollImg = document.getElementById("rollImg");
var currentL = -index * 560;
CustomAnimate.animate(rollImg, {
left: currentL
}, function() {
console.log(index, "wwwww");
if (index > 4) {
index = 1;
currentL = -index * 560;
rollImg.style.left = currentL + 'px';
}
});;
}
setInterval(()=>{
animation();
},2000)
</script>
</body>
</html>