I have "div" element with specified width and height expressed in percents in CSS.
I would like to get by JS script its width and height expressed in pixels. It's even possible?
You can use
el.clientHeight;
el.clientWidth;
( el
is a reference to the element)
Note those properties were first introduced in the MS IE DHTML object model. More recently they were standardized in CSSOM View Module , W3C Working Draft 22 February 2008.
Those properties were widely supported. However, it's possible than an old non-MS compliant browser doesn't support them. In those cases, you can use getComputedStyle
:
function findSize(el, size) {
/* size must be 'width' or ' height' */
return window.getComputedStyle
? getComputedStyle(el,null).getPropertyValue(size)
: el['client'+size.substr(0,1).toUpperCase() + size.substr(1)] + 'px';
}
findSize(el, 'width');
findSize(el, 'height');
Browser support of getComputedStyle
and clientHeight
/ clientWidth
way is at least:
| IE | Firefox | Chrome | Safari | Opera
-----------------|-----------------------------------------
getComputedStyle | 9 | <=3 | 1 | <=4 | <=10
client | <=5 | <=3 | 1 | <=4 | <=10
( <=n
means that it's supported at least from version n
, but I couldn't test previous versions)
Use window.getComputedStyle()
for this
<div style="wdith:50%">50% width</div>
(function() {
var div = document.getElementsByTagName("div")[0];
console.log(window.getComputedStyle(div, null)["width"]);
}())
Supported by all major browsers and IE9+. For lower versions of IE have a look at currentStyle
jQuery 键是:
$("#div").width($("#div").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.