Detect inline/block type of a DOM element

后端 未结 3 1671
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: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)

提交回复
热议问题