1. 程式人生 > >變速動畫函數封裝增加任意多個屬性、透明度和層級

變速動畫函數封裝增加任意多個屬性、透明度和層級

是否 false win 定時器 flag set -c 屬性 .get

//計算後的樣式屬性---- 一個元素的任意的一個樣式屬性值
function getStyle(element,attr) {
//判斷這個瀏覽器是否支持這個方法
return window.getComputedStyle?window.getComputedStyle(element,null)[attr]:element.currentStyle[attr];
}
//勻速動畫
function animate(element,json,fn) { //element--元素 attr--屬性名字 target--目標位置
//清理定時器
clearInterval(element.timeId);
element.timeId=setInterval(function () {
var flag=true;//默認,假設,全部到達目標
for(var attr in json){
//判斷這個屬性中attr中是不是opacity
if (attr=="opacity"){
//獲取元素的當前的透明度,當前的透明度放大100倍
var current=getStyle(element,attr)*100;
//目標的透明度放大100倍
var target=json[attr]*100;
var step=(target-current)/10;
step=step>0?Math.ceil(step):Math.floor(step);
current+=step;
element.style[attr]=current/100;
}else if(attr=="zIndex"){ //判斷這個屬性attr中是不是zIndex
//層級改變就是直接改變這個屬性的值
element.style[attr]=json[attr];
}else {
//獲取元素當前位置
var current=parseInt(getStyle(element,attr));//數字類型
//當前的屬性對應的目標值
var target=json[attr];
//移動的步數
var step=(target-current)/10;
step=step>0?Math.ceil(step):Math.floor(step);
current+=step;
element.style[attr]=current+"px";
}
//判斷是否到達目標
if(current!=target){
flag=false;
}
}
if(flag){
//清理計時器
clearInterval(element.timeId);
//回調函數,所有屬性達到目標後才能使用
if(fn){
fn();
}
}

變速動畫函數封裝增加任意多個屬性、透明度和層級