function animate(elem,targetJson,time){
/*
targetjson{
'left':600px,
'top':700px,
}
总的时间有,我们可以假定运动间隔为50ms,那么总的运动次数可以求出
需要根据targetJson求出对应的semaphorejson,然后,然后求出stepjson
有了三个 json可以开始运动,每次运动就在semaphorejson加上一个stepJson
* */
//假定运动间隔为50ms
var interval = 50;
//根据用户传入的 时间/interval就是总次数
var maxcount = time / interval;
//声明信号量(最初状态json)
var semaphoreJson = {};
//根据target求出最初的semaphoreJson
for(var k in targetJson){
//根据targetJson中的k取出元素最初状态的数值
semaphoreJson[k] = parseFloat(fetchComputedStyle(elem,k));
//targetJson中的px取掉
targetJson[k] = parseFloat(targetJson[k]);
}
//步长stepjson
var stepjson = {};
for(var k in targetJson){
stepjson[k] = (targetJson[k] - semaphoreJson[k]) / maxcount;
}
// console.log(semaphoreJson,targetJson,stepjson);
//运动函数
var count = 0;
var timer = setInterval(function(){
count++;
//semaphoreJson每次加上stepJson
for(var k in targetJson){
if(k == 'opacity'){
semaphoreJson[k] += stepjson[k];
elem.style[k] = semaphoreJson[k];
}else{
semaphoreJson[k] += stepjson[k];
elem.style[k] = semaphoreJson[k] + 'px';
}
}
for(var k in semaphoreJson){
console.log(k+':'+semaphoreJson[k]);
}
//当步数狗时,拉终停表,直接把targerJson的值赋值给元素
if(count == maxcount){
for(var k in targetJson){
if(k == 'opacity'){
elem.style[k] = targetJson[k];
}else{
elem.style[k] = targetJson[k] + 'px';
}
}
clearInterval(timer);
}
},interval);
}
function fetchComputedStyle(obj , property){
//能力检测
if(window.getComputedStyle){
//现在要把用户输入的property中检测一下是不是驼峰,转为连字符写法
//强制把用户输入的词儿里面的大写字母,变为小写字母加-
//paddingLeft → padding-left
property = property.replace(/([A-Z])/g , function(match,$1){
return "-" + $1.toLowerCase();
});
return window.getComputedStyle(obj)[property];
}else{
//IE只认识驼峰,我们要防止用户输入短横,要把短横改为大写字母
//padding-left → paddingLeft
property = property.replace(/\-([a-z])/g , function(match,$1){
return $1.toUpperCase();
});
return obj.currentStyle[property];
}
}
animate函数
最新推荐文章于 2021-06-24 09:52:47 发布