[英]CSS convert percent to pixels
I have "div" element with specified width and height expressed in percents in CSS.我在 CSS 中有指定宽度和高度的“div”元素,以百分比表示。
I would like to get by JS script its width and height expressed in pixels.我想通过 JS 脚本获得以像素表示的宽度和高度。 It's even possible?甚至有可能吗?
You can use您可以使用
el.clientHeight;
el.clientWidth;
( el
is a reference to the element) ( el
是对元素的引用)
Note those properties were first introduced in the MS IE DHTML object model.请注意,这些属性最初是在 MS IE DHTML 对象模型中引入的。 More recently they were standardized in CSSOM View Module , W3C Working Draft 22 February 2008.最近,它们在 2008 年 2 月 22 日的 W3C 工作草案CSSOM 视图模块中进行了标准化。
Those properties were widely supported.这些属性得到了广泛的支持。 However, it's possible than an old non-MS compliant browser doesn't support them.但是,旧的非 MS 兼容浏览器可能不支持它们。 In those cases, you can use getComputedStyle
:在这些情况下,您可以使用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:浏览器对getComputedStyle
和clientHeight
/ clientWidth
方式的支持至少是:
| 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) ( <=n
表示至少从版本n
支持它,但我无法测试以前的版本)
Use window.getComputedStyle()
for this为此使用window.getComputedStyle()
<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+.支持所有主流浏览器和 IE9+。 For lower versions of IE have a look at currentStyle
对于较低版本的 IE,请查看currentStyle
jQuery 键是:
$("#div").width($("#div").width());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.