Detect inline/block type of a DOM element

后端 未结 3 1663
Happy的楠姐
Happy的楠姐 2020-12-08 20:27

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 \'

相关标签:
3条回答
  • 2020-12-08 21:09

    The traditional and rather ugly way of doing this is to consult a list of element names for block-level elements:

    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);
    }
    
    0 讨论(0)
  • 2020-12-08 21:10

    Consider that a block element may have been added to the dom containing a class with display:none. In that case you would need to know the default for that element. The following code gets a default style setting for an element (http://jsfiddle.net/jameswestgate/qBV5c/embedded/):

    function getDefaultStyle(nodeName, property) {
        var div = document.createElement('div');
        div.setAttribute('style','position:absolute; left:-9999px;');
    
        var el = document.createElement(nodeName);
        div.appendChild(el);
        document.body.appendChild(div);
    
        var result = getComputedStyle(el, null).getPropertyValue(property);
        document.body.removeChild(div); 
    
        return result;
    }
    

    In this case call it using the nodeName of eg p and the display property which should return block or inline

    getDefaultStyle('p', 'display'); //returns block
    

    (For IE browsers, you need to use currentStyle instead of getComputedStyle)

    0 讨论(0)
  • 2020-12-08 21:15

    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.

    0 讨论(0)
提交回复
热议问题