轮播图运动框架
前言:这个方法可以完成绝大多数的平滑运动效果,如果要修改效果,请调整计时器的间隔时间或者speed。 :)
代码
//运动框架
//语法startMove(obj,{},fn);
//obj:对象 - {}:名是属性,值是值 - fn:结束后执行的函数
//例如starMove(div1 , {width:"300",height:300}, function(){
// alert("nice");
//})
function getStyle(obj, name){
if(obj.currentStyle){
return obj.currentStyle[name];
}else{
return getComputedStyle(obj, false)[name];
}
}
function starMove(obj, json, fnEnd){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
let if_stop=true;
for(let attr in json){
let cur;
if(attr=='opacity'){
cur=Math.round(parseFloat(getStyle(obj,attr))*100);
}else{
cur=parseInt(getStyle(obj,attr));
}
let speed=(json[attr]-cur)/6;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(cur!=json[attr]){
if_stop=false;
if(attr=='opacity'){
obj.style.opacity = (cur+speed)/100;
}else{
obj.style[attr]=cur+speed+'px';
}
}
}
if(if_stop){
clearInterval(obj.timer);
if(fnEnd)fnEnd();
}
},30)
}
将这个框架引入之后即可测试效果,下面给出一个案例
<div id="div1" style="position:absolute; width: 10px; padding: 50px; background-color: skyblue;"></div>
let oDiv = document.getElementById('div1');
starMove(oDiv,{left:'400',width:'100',height:'100'},function(){
alert('运动完毕~');
});
ps:c3新增的transition属性也可以做到平滑过渡