Home>Article>Web Front-end> Detailed explanation of examples of motion framework encapsulation in js

Detailed explanation of examples of motion framework encapsulation in js

零下一度
零下一度 Original
2017-06-25 09:15:50 1310browse
     //获取非行间样式的封装
function setStyle(obj,name){
          // 考虑兼容性问题
if(obj.currentStyle){//不兼容火狐和谷歌
return obj.currentStyle[name];
}else{
return getComputedStyle(obj,false)[name];//不兼容IE
}
}
 function move(obj,json,complete) {
// 用计时器前先清除,防止多次点击
clearInterval(obj.timer);
// 设置complete的默认值
var complete=complete||{};//如果有就是用户传入的值,否则就是一个空对象
complete.dur=complete.dur||2000;//时间:如果有就是用户传入的值,否则默认2000
complete.easing=complete.easing||"linear";//运动方式:如果有就是用户传入的值,否则默认匀速
        //总步数=总时间÷计时器设定的时间
var count = parseInt(complete.dur / 30);
      //起始位置,先定义一个json
var start={};
      //总距离=传入的距离-起始距离
var dis={};
// 因为传入了多个起始目标和多个终点目标,所以先循环
for(name in json){
start[name]=parseFloat(setStyle(obj,name));
dis[name]=json[name]-start[name];
}
// 每步运动的距离=总距离÷总步数
// var spen = dis[name] / count;
// 定义起始步数
var n = 0;
obj.timer = setInterval(function () {
n++;
for(name in json){
var a=n/count;
switch(complete.easing){//判断
case "linear":
var cur=start[name] + a * dis[name];//起始位置+当前运动的距离*总距离÷总步数,数学中先乘后除或先除后乘结果都一样
break;
case "ease-in":
var cur=start[name] + Math.pow(a,3) * dis[name];
break;
case "ease-out":
var a=1-n/count;
var cur=start[name] +(1-Math.pow(a,3)) * dis[name];
break;
}
// 把当前运动的位置保存

// 判断属性是不是透明度,透明度不用加单位
if(name=='opacity'){
obj.style[name]=cur;
// 兼容IE低版本,IE的透明度是1到100
obj.style.filter='alpha('+cur*100+')';
}else {
obj.style[name] = cur + "px";
}
}

// 判断运动是否完成
if (n == count) {
// 完成后清除定时器,停止运动
clearInterval(obj.timer);
// 判断用户是否传入回调函数
complete.fn && complete.fn();
}
}, 30);
}
     

The above is the detailed content of Detailed explanation of examples of motion framework encapsulation in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn