How to get inherited CSS value using Javascript?

I am trying to get the value of an inherited CSS property using Javascript. I could not find a comprehensive answer.

CSS example:

div {
    width: 80%;
}

Layout Example:

<div id="mydiv"> Some text </div>

Using javascript (jQuery or native), I need to get the width of the element - not in pixels, but in the string "80%".

$('#mydiv').css('width'); // returns in px
$('#mydiv')[0].style.width // empty string
getComputedStyle($('#mydiv')[0]).width // returns in px

The reason I need the value as a string is because I need to copy the style to another element. If it is declared as a percentage, the other value must be a percentage. If it is declared in px, the other value should be in px.

The real trick is that this property can be inherited rather than explicitly point to an element (as in my example).

Does anyone have any ideas?

+5
source share
4 answers

, . - :

var widthpx = getComputedStyle($('#mydiv')[0]).width;
var parentWidth = $('#mydiv').parent().css('width')

var width = ( 100 * parseFloat(widthpx) / parseFloat(parentWidth) ) + '%';
+3

, quirksmode.org.

function getStyle(el, styleProp)    {
    var x = document.getElementById(el);
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    return y;
}

, . styleProp -, , . , Opera .

+5

offSetWidth offsetWidth offsetParent .

0

This binds the event handler to the element for the event clickand warns the relative width of the element compared to its parent element.

​$('#mydiv').on('click', function () {

    //element width divided by parent width times 100 to make a percentage
    alert(Math.round($(this).width() / $(this).parent().width() * 100) + '%');
});​​​​​​​​​​

Here is a demo: http://jsfiddle.net/X67p5/

0
source

All Articles