While walking HTML5 DOM tree I want to determine whether each element is a block level element or inline element.

var divElement = document.getElementById('foo');
alert(divElement.style.display)
alert(window.getComputedStyle(divElement, null).getPropertyValue('display'))

I see that the first alert displays a null-string while the second alert displays 'block', so I think the second technique is what I need to use. Here is a jsfiddle: http://jsfiddle.net/UaFpv/

我想知道使用window.getComputedStyle(divElement, null).getPropertyValue('display')做我的工作是否有任何弊端,例如跨浏览器兼容性问题等。是否有其他技术可以解决此问题?

最佳答案

IE旧版本不支持getComputedStyle。对于IE,请使用 currentStyle 属性:

divElement.currentStyle['display'];

在您的代码中实现:
var divElement = document.getElementById('foo');
var displayStyle;
if (divElement) { // Only if the element exists
    if (window.getComputedStyle) {
        displayStyle = window.getComputedStyle(divElement, null).getPropertyValue('display');
    } else {
        displayStyle = divElement.currentStyle.display;
    }
}
alert(displayStyle);

07-24 17:09