javascript CSS 将百分比转换为像素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12165696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS convert percent to pixels
提问by Jacek
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?
我有指定宽度和高度的“div”元素,以 CSS 中的百分比表示。
我想通过 JS 脚本获得以像素表示的宽度和高度。甚至有可能吗?
回答by Oriol
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. More recently they were standardized in CSSOM View Module, W3C Working Draft 22 February 2008.
请注意,这些属性最初是在 MS IE DHTML 对象模型中引入的。最近,它们在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. In those cases, you can use getComputedStyle
:
这些属性得到了广泛的支持。但是,旧的非 MS 兼容浏览器可能不支持它们。在这些情况下,您可以使用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
意味着至少从 version 开始支持它n
,但我无法测试以前的版本)
回答by Andreas
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
所有主流浏览器和 IE9+ 均支持。对于较低版本的 IE 看看currentStyle
回答by Shlomi Aharoni
The jQuery key is :
jQuery 键是:
$("#div").width($("#div").width());