问题:在js动画中,如果元素设置了border,padding等,获取到的样式是盒子的样式,这样会影响动画的正常显示。
解决方案一:在元素的行内添加样式 如
<div style="width=200px"> <div>
解决方案二:通过getstyle()方法获取样式
<script type="text/javascript">
//哪个元素
//哪个样式 function getStyle(obj, attr)
{
if(obj.currentStyle)
{
return obj.currentStyle[attr];
}
else
{
return getComputedStyle(obj, false)[attr];
}
} window.onload=function ()
{
var oDiv=document.getElementById('div1'); alert(getStyle(oDiv, 'backgroundColor'));
}
</script> <div id="div1"></div> //获取样式简洁版
function getStyle(obj, attr) {
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, false)[attr];
}
//opacity 设置透明度
function setOpacity(elem, value) {
elem.filters ? elem.style.filter = 'alpha(opacity=' + value + ')' : elem.style.opacity = value / 100;
} //完美版
function css(obj, attr, value){
switch (arguments.length){
case 2:
if(typeof arguments[1] == "object"){
for (var i in attr) i == "opacity" ? (obj.style["filter"] = "alpha(opacity=" + attr[i] + ")", obj.style[i] = attr[i] / 100) : obj.style[i] = attr[i];
}else{
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr]
}
break;
case 3:
attr == "opacity" ? (obj.style["filter"] = "alpha(opacity=" + value + ")", obj.style[attr] = value / 100) : obj.style[attr] = value;
break;
}
};