get CSS rule's percentage value in jQuery

后端 未结 12 1342
一个人的身影
一个人的身影 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:30

    Building on timofey's excellent and surprising solution, here is a pure Javascript implementation:

    function cssDimensions(element)
      var cn = element.cloneNode();
      var div = document.createElement('div');
      div.appendChild(cn);
      div.style.display = 'none';
      document.body.appendChild(div);
      var cs = window.getComputedStyle
        ? getComputedStyle(cn, null)
        : cn.currentStyle;
      var ret = { width: cs.width, height: cs.height };
      document.body.removeChild(div);
      return ret;
    }
    

    Hope it's helpful to someone.

    0 讨论(0)
  • 2020-11-22 08:31

    There's no built-in way, I'm afraid. You can do something like this:

    var width = ( 100 * parseFloat($('.largeField').css('width')) / parseFloat($('.largeField').parent().css('width')) ) + '%';
    
    0 讨论(0)
  • 2020-11-22 08:31

    You could access the document.styleSheets object:

    <style type="text/css">
        .largeField {
            width: 65%;
        }
    </style>
    <script type="text/javascript">
        var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
        for (var i=0; i < rules.length; i++) {
            var rule = rules[i];
            if (rule.selectorText.toLowerCase() == ".largefield") {
                alert(rule.style.getPropertyValue("width"));
            }
        }
    </script>
    
    0 讨论(0)
  • 2020-11-22 08:33

    Most easy way

    $('.largeField')[0].style.width
    
    // >>> "65%"
    
    0 讨论(0)
  • 2020-11-22 08:34

    You could put styles you need to access with jQuery in either:

    1. the head of the document directly
    2. in an include, which server side script then puts in the head

    Then it should be possible (though not necessarily easy) to write a js function to parse everything within the style tags in the document head and return the value you need.

    0 讨论(0)
  • 2020-11-22 08:36

    This is most definitely possible!

    You must first hide() the parent element. This will prevent JavaScript from calculating pixels for the child element.

    $('.parent').hide();
    var width = $('.child').width();
    $('.parent').show();
    alert(width);
    

    See my example.

    Now... I wonder if I'm first to discover this hack:)

    Update:

    One-liner

    element.clone().appendTo('body').wrap('<div style="display: none"></div>').css('width');
    

    It will leave behind a hidden element before the </body> tag, which you may want to .remove().

    See an example of one-liner.

    I'm open to better ideas!

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