Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

javascript - Detect inline/block type of a DOM element

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...