如何检测DOM元素是JavaScript块还是内联?

例如,是否有一个函数/属性为“<a>”标签返回“内联”(或为“<p>”标签返回“block”)?

谢谢。

最佳答案

您可以使用 getComputedStyle() currentStyle 来获取元素的计算样式。应该这样做:

function getDisplayType (element) {
    var cStyle = element.currentStyle || window.getComputedStyle(element, "");
    return cStyle.display;
}

为了更清楚一点,计算的样式包含每个样式属性的值,即使对于那些未设置样式属性的样式也是如此。这些值将是默认值,因此在使用无样式<a>元素的情况下,display将返回inline:
function getElementDefaultDisplay(tag) {
    var cStyle,
        t = document.createElement(tag),
        gcs = "getComputedStyle" in window;

    document.body.appendChild(t);
    cStyle = (gcs ? window.getComputedStyle(t, "") : t.currentStyle).display;
    document.body.removeChild(t);

    return cStyle;
}

在最新的Firefox,Chrome和IE7 / IE8中进行了测试。

结果:



更新:对进行了编辑,以优先考虑IE9中的标准合规性/ getComputedStyle(),它支持两种方法。

07-24 15:26
查看更多