abe*_*ier 21 javascript dom inline
如何检测DOM元素是块还是内嵌javascript?
例如,是否有一个函数/属性为' <a>'标签返回'inline' (或''标签'为'block' <p>)?
谢谢.
And*_*y E 30
您可以使用getComputedStyle()和currentStyle获取元素的计算样式.这应该这样做:
function getDisplayType (element) {
var cStyle = element.currentStyle || window.getComputedStyle(element, "");
return cStyle.display;
}
Run Code Online (Sandbox Code Playgroud)
为了更清楚一点,计算样式包含每个样式属性的值,即使对于那些没有样式属性集的样式也是如此.这些值将是默认值,因此在非样式<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;
}
Run Code Online (Sandbox Code Playgroud)
测试了最新的Firefox,Chrome和IE7/IE8.
结果:
Run Code Online (Sandbox Code Playgroud)> getElementDefaultDisplay("a") inline > getElementDefaultDisplay("div") block
更新:编辑以优先考虑getComputedStyle()IE9中的标准符合性/ IE9,它支持这两种方法.
执行此操作的传统且相当丑陋的方法是查询块级元素的元素名称列表:
var blockRegex = /^(address|blockquote|body|center|dir|div|dl|fieldset|form|h[1-6]|hr|isindex|menu|noframes|noscript|ol|p|pre|table|ul|dd|dt|frameset|li|tbody|td|tfoot|th|thead|tr|html)$/i;
function isBlockLevel(el) {
return blockRegex.test(el.nodeName);
}
Run Code Online (Sandbox Code Playgroud)