get CSS rule's percentage value in jQuery

后端 未结 12 1363
一个人的身影
一个人的身影 2020-11-22 08:22

Let\'s say the rule is as follows:

.largeField {
    width: 65%;
}

Is there a way to get \'65%\' back somehow, and not the pixel value?

12条回答
  •  情话喂你
    2020-11-22 08:41

    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 to get 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
    }
    

提交回复
热议问题