检测DOM元素的内联/块类型 [英] Detect inline/block type of a DOM element

查看:134
本文介绍了检测DOM元素的内联/块类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,是否有一个函数/属性返回'inline'为'< a> '标签(或'< p> '标签的'block')



谢谢。

解决方案

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

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

要清楚一点,计算的样式包含每个样式属性的值,甚至对于没有设置样式属性的那些。这些值将是默认值,因此在未分类的< a> 元素的情况下,显示将返回 inline

  function getElementDefaultDisplay(tag){
var cStyle ,
t = document.createElement(tag),
gcs =getComputedStyle在窗口中;

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

return cStyle;
}

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



结果:


 > getElementDefaultDisplay(a)
inline
> getElementDefaultDisplay(div)


更新:编辑为优先于符合标准/ getComputedStyle()在IE9中,它支持两种方法。


How to detect whether a DOM element is block or inline with javascript?

For example, is there a function/property which returns 'inline' for a '<a>' tag (or 'block' for a '<p>' tag)?

Thank you.

解决方案

You can go with getComputedStyle() and currentStyle to get the calculated styles for an element. This should do it:

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

To be a little clearer, computed styles contain values for every style property, even for those that don't have a style property set. Those values will be the default value so in the case of an unstyled <a> element, display will return 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;
}

Tested in latest Firefox, Chrome and IE7/IE8.

Results:

> getElementDefaultDisplay("a")
inline
> getElementDefaultDisplay("div")
block

Update: edited to give preference to standards compliance/getComputedStyle() in IE9, which supports both methods.

这篇关于检测DOM元素的内联/块类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆