[英]CSS convert percent to pixels
我在 CSS 中有指定宽度和高度的“div”元素,以百分比表示。
我想通过 JS 脚本获得以像素表示的宽度和高度。 甚至有可能吗?
您可以使用
el.clientHeight;
el.clientWidth;
( el
是对元素的引用)
请注意,这些属性最初是在 MS IE DHTML 对象模型中引入的。 最近,它们在 2008 年 2 月 22 日的 W3C 工作草案CSSOM 视图模块中进行了标准化。
这些属性得到了广泛的支持。 但是,旧的非 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');
浏览器对getComputedStyle
和clientHeight
/ clientWidth
方式的支持至少是:
| IE | Firefox | Chrome | Safari | Opera
-----------------|-----------------------------------------
getComputedStyle | 9 | <=3 | 1 | <=4 | <=10
client | <=5 | <=3 | 1 | <=4 | <=10
( <=n
表示至少从版本n
支持它,但我无法测试以前的版本)
<div style="wdith:50%">50% width</div>
(function() {
var div = document.getElementsByTagName("div")[0];
console.log(window.getComputedStyle(div, null)["width"]);
}())
支持所有主流浏览器和 IE9+。 对于较低版本的 IE,请查看currentStyle
jQuery 键是:
$("#div").width($("#div").width());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.