Getting values of global stylesheet in jQuery

后端 未结 4 1745
长发绾君心
长发绾君心 2020-12-12 04:58

When I use a style sheet definition like this on HTML page scope

#sideBar {
  float: left;
  width: 27.5%;
  min-width: 275;
  ... 
}

the f

4条回答
  •  盖世英雄少女心
    2020-12-12 05:18

    There's nothing in jQuery, and nothing straightforward even in javascript. Taking timofey's answer and running with it, I created this function that works for getting any properties you want:

    // gets the style property as rendered via any means (style sheets, inline, etc) but does *not* compute values
    // domNode - the node to get properties for 
    // properties - Can be a single property to fetch or an array of properties to fetch
    function getFinalStyle(domNode, properties) {
        if(!(properties instanceof Array)) properties = [properties]
    
        var parent = domNode.parentNode
        if(parent) {
            var originalDisplay = parent.style.display
            parent.style.display = 'none'
        }
        var computedStyles = getComputedStyle(domNode)
    
        var result = {}
        properties.forEach(function(prop) {
            result[prop] = computedStyles[prop]
        })
    
        if(parent) {
            parent.style.display = originalDisplay
        }
    
        return result
    }
    

    The trick used here is to hide its parent, get the computed style, then unhide the parent.

提交回复
热议问题