封装getStyle (获取样式currentStyle getComputedStyle兼容处理)

时间:2022-06-23 06:48:12

<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;
	}
};