简体   繁体   中英

Getting the width of an html element in percent % with jQuery

If I alert the element which has a css selector set to width:100% I get it's with in px , is there some way to get it in % as set from css, I need it to fix some script with fluid layouts.

// css
.my-element {
    width:100%;
}

// javascript
alert('width: '+$('.my-element').css('width'));
// this alerts "width: 1116px" instead of "width: 100%"

Maybe something like this is always true?

alert($('.my-element').outerWidth() == $('.my-element').parent().outerWidth());
function percentwidth(elem){
    var pa= elem.offsetParent || elem;
    return ((elem.offsetWidth/pa.offsetWidth)*100).toFixed(2)+'%';
}

You can get the width in percentage by two methods.

Live Demo

With jQuery use jQuery 1.3.2 and you will get 100%.

alert($('.my-element').css('width'))​;

With javascript by setting width in style attribute of the tag like this

<div id="div2" style="width:100%"></div>

div2 = document.getElementById('div2');

alert("Width of div2 with style = " + div2.style.width);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM