get CSS rule's percentage value in jQuery

jquery css

76703 просмотра

12 ответа

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?

Thanks.

EDIT: Unfortunately using DOM methods is unreliable in my case, as I have a stylesheet which imports other stylesheets, and as a result the cssRules parameter ends up with either null or undefined value.

This approach, however, would work in most straightforward cases (one stylesheet, multiple separate stylesheet declarations inside the head tag of the document).

Автор: montrealist Источник Размещён: 12.11.2019 09:55

Ответы (12)


49 плюса

Решение

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')) ) + '%';
Автор: Adam Lassek Размещён: 13.04.2009 04:09

114 плюса

Most easy way

$('.largeField')[0].style.width

// >>> "65%"
Автор: redexp Размещён: 03.05.2012 01:57

82 плюса

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!

Автор: timofey.com Размещён: 09.11.2013 07:56

44 плюса

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>
Автор: Gumbo Размещён: 13.04.2009 04:27

18 плюса

Late, but for newer users, try this if the css style contains a percentage:

$element.prop('style')['width'];
Автор: ddanone Размещён: 07.06.2016 10:09

10 плюса

A jQuery plugin based on Adams answer:

(function ($) {

    $.fn.getWidthInPercent = function () {
        var width = parseFloat($(this).css('width'))/parseFloat($(this).parent().css('width'));
        return Math.round(100*width)+'%';
    };

})(jQuery);

$('body').html($('.largeField').getWidthInPercent());​​​​​

Will return '65%'. Only returns rounded numbers to work better if you do like if (width=='65%'). If you would have used Adams answer directly, that hadn't worked (I got something like 64.93288590604027). :)

Автор: Leonard Pauli Размещён: 04.09.2012 07:15

3 плюса

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.

Автор: Gregory Magarshak Размещён: 06.04.2016 07:29

1 плюс

I have a similar issue in Getting values of global stylesheet in jQuery, eventually I came up with the same solution as above.

Just wanted to crosslink the two questions so others can benefit from later findings.

Автор: Horst Walter Размещён: 20.08.2011 11:48

0 плюса

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.

Автор: wheresrhys Размещён: 13.04.2009 04:24

0 плюса

You can use the css(width) function to return the current width of the element.

ie.

var myWidth = $("#myElement").css("width");

See also: http://api.jquery.com/width/ http://api.jquery.com/css/

Автор: user267867 Размещён: 06.03.2010 10:42

0 плюса

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
}
Автор: B T Размещён: 03.10.2016 04:11

0 плюса

Convert from pixels to percentage using cross multiplication.

Formula Setup:

1.) (element_width_pixels/parent_width_pixels) = (element_width_percentage / 100)

2.) element_width_percentage = (100 * element_width_pixels) / parent_width_pixels

The actual code:

<script>

   var $width_percentage = (100 * $("#child").width()) / $("#parent").width();

</script>
Автор: Zachary Horton Размещён: 08.12.2017 06:59
Вопросы из категории :
32x32