JS获取标签最终样式

我今天写点击隐藏子菜单时,获取不到obj.style.display属性,经过查找资料,发现是因为这样子只能获取内联样式的原因。

要获取最终样式,IE中可以使用currentStyle,在chrome等浏览器中可以使用document.defaultView。代码如下:

function getFinalStyle(obj, styleName){
	if (obj.currentStyle){
		var y = obj.currentStyle[styleName];
		console.log("currentStyle");
	}
	else if (document.defaultView){
		var y = document.defaultView.getComputedStyle(obj,null).getPropertyValue(styleName);
		console.log("getComputedStyle");
	}
	return y;
}

document.defaultView用来判断是否有这个对象。也可以换成window.getComputedStyle。

写了一段代码放在浏览器中测试了一下。是可以的。

<!DOCTYPE html>
<html>
<head>
<style>
.myDiv{
	height:500px;
	width:500px;
	background:#00ff00;
	display:block;
}
</style>
<script>
function showDiv(obj){
	obj.innerHTML = "OBJ.STYLE<br>"
					+ "height: " + obj.style.height + "<br>"
					+ "width: " + obj.style.width + "<br>"
					+ "background: " + obj.style.background + "<br>"
					+ "display: " + obj.style.display + "<br>"
					+ "CURRENTSTYLE<br>"
					+ "height: " + getFinalStyle(obj, "height") + "<br>"
					+ "width: " + getFinalStyle(obj, "width") + "<br>"
					+ "background: " + getFinalStyle(obj, "background") + "<br>"
					+ "display: " + getFinalStyle(obj, "display") + "<br>";
}
function getFinalStyle(obj, styleName){
	if (obj.currentStyle){
		var y = obj.currentStyle[styleName];
		console.log("currentStyle");
	}
	else if (window.getComputedStyle){
		var y = document.defaultView.getComputedStyle(obj,null).getPropertyValue(styleName);
		console.log("getComputedStyle");
	}
	return y;
}
</script>
</head>
<body>
<div class="myDiv" οnclick="showDiv(this)"></div>
</body>
</html>

最近经常遇到浏览器不兼容的问题。真心痛苦啊

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值