我今天写点击隐藏子菜单时,获取不到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>
最近经常遇到浏览器不兼容的问题。真心痛苦啊