标签:宽高 parse function win attr star var math onload
//获取元素属性值的封装
function getStyle(obj,name){
if(obj.currentStyle){
return obj.currentStyle[name];
}else{
return getComputedStyle(obj,false)[name];
}
}
//运动框架
function startMove(obj,json,fn){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var bStop = true;
for(var attr in json){
//offsetHeight有一个bug,就是无法准确获取元素宽高,当有body,padding或者margin的时候,就无法正确获取宽高,所以用新的方法来获取宽高。
var curSty = 0;
if(attr == ‘opacity‘){
//Math.round()四舍五入,用来让透明度误差降低
curSty = Math.round(parseFloat(getStyle(obj,attr))*100);
}else{
curSty = parseInt(getStyle(obj,attr));
}
var speed = (json[attr]-curSty)/4
speed = speed>0?Math.ceil(speed):Math.floor(speed);
if(curSty != json[attr]){
bStop = false;
}
if(attr == ‘opacity‘){
obj.style.filter = ‘alpha(opacity:‘+(curSty + speed)+‘)‘
obj.style.opacity = (curSty + speed)/100
}else{
obj.style[attr] = curSty + speed + ‘px‘;
}
}
if(bStop){
clearInterval(obj.timer);
if(fn)fn();
}
},30);
}
HTML:
<input type="button" id="btn" value="同时变化" />
<div id="div1"></div>
CSS:
#div1{width: 100px;height: 100px;background: red;filter: alpha(opacity:30);opacity: 0.3;}
JS:
window.onload = function(){
var oDiv1 = document.getElementById(‘div1‘);
var oBtn = document.getElementById(‘btn‘);
oBtn.onclick = function(){
startMove(oDiv1,{height:300,opacity:100},function(){
console.log(oDiv1.offsetHeight);
startMove(oDiv1,{width:400},function(){
console.log(oDiv1.offsetWidth)
});
});
}
}
标签:宽高 parse function win attr star var math onload
原文地址:http://www.cnblogs.com/cjw-jxd/p/7466520.html