CSS将百分比转换为像素

Jac*_*cek 4 javascript css

我有"div"元素,其中指定的宽度和高度以CSS中的百分比表示.
我想通过JS脚本获得以像素表示的宽度和高度.它甚至可能吗?

Ori*_*iol 5

您可以使用

el.clientHeight;
el.clientWidth;
Run Code Online (Sandbox Code Playgroud)

(el是对元素的引用)

演示

请注意,这些属性最初是在MS IE DHTML对象模型中引入的.最近,他们在CSSOM View Module,W3C Working Draft 22 2008年2月进行了标准化.

这些属性得到广泛支持.但是,它可能比旧的非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');
Run Code Online (Sandbox Code Playgroud)

演示

浏览器支持的getComputedStyleclientHeight/ clientWidth方法是至少包括:

                 | IE  | Firefox | Chrome | Safari | Opera
-----------------|-----------------------------------------
getComputedStyle | 9   | <=3     | 1      | <=4    | <=10
client           | <=5 | <=3     | 1      | <=4    | <=10
Run Code Online (Sandbox Code Playgroud)

(<=n意味着至少从版本支持它n,但我无法测试以前的版本)