平時工作中寫網頁涉及的運動往往都非常簡單,比如改變寬高,透明度,位置,是最常用的幾種形式,為了省事,整合了下,於是就有了下面這個東東:
兼容:IE系列、chrome、firefox、opera、Safari、360
/*
javascript簡易運動
Move.action(dom對象,json格式屬性值對,緩動參考值,回調方法)
示例:
var box = document.getElementById('Ele');
Move.action(box,{width:500,height:200,left:200,top:100,marginLeft:10,opacity:.5},5,function(){
console.log('end');
});
*/
var Move = {
version: '1.5',
//判斷是否空對象
isEmptyObject: function(obj) {
for (var attr in obj) {
return false;
}
return true;
},
//取CSS樣式值
getStyle: function(obj, attr) {
if (obj.currentStyle) { //IE
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj, null)[attr];
}
},
//運動
action: function(obj, json, sv, callback) {
_this = this;
//obj是否為空
if (_this.isEmptyObject(obj)) {
return false;
}
//運動開始
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var isAllCompleted = true, //假設全部運動都完成了
speed, //速度
attrValue, //當前值
targetV; //目標值
for (attr in json) {
attrValue = _this.getStyle(obj, attr);
switch (attr) {
case 'opacity':
attrValue = Math.round((isNaN(parseFloat(attrValue)) ? 1 : parseFloat(attrValue)) * 100);
speed = (json[attr] * 100 - attrValue) / (sv || 4);
targetV = json[attr] * 100;
break;
default:
attrValue = isNaN(parseInt(attrValue)) ? 0 : parseInt(attrValue);
speed = (json[attr] - attrValue) / (sv || 4);
targetV = json[attr];
}
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
//如果循環過程中存在尚未結束的運動,isAllCompleted為假
if (attrValue != targetV) {
isAllCompleted = false;
}
switch (attr) {
case 'opacity':
{
obj.style.filter = "alpha(opacity=" + (attrValue + speed) + ")";
obj.style.opacity = (attrValue + speed) / 100;
};
break;
default:
obj.style[attr] = attrValue + speed + 'px';
}
}
//所有循環結束後,只有當全部運動結束後(isAllCompleted=true)時才關閉定時器
if (isAllCompleted) {
clearInterval(obj.timer);
if (typeof callback === 'function') {
callback();
}
}
}, 30);
}
};
以上就是描述了javascript實現網頁中涉及的簡易運動的方法,希望對大家實現javascript簡易運動有所啟發。