我有“div”元素,其中指定的宽度和高度以CSS中的百分比表示.
我想通过JS脚本获得以像素表示的宽度和高度.它甚至可能吗?
解决方法:
您可以使用
el.clientHeight;
el.clientWidth;
(elis是对元素的引用)
请注意,这些属性最初是在MS IE DHTML对象模型中引入的.最近,他们在CSSOM View Module,W3C工作草案2008年2月22日进行了标准化.
这些属性得到广泛支持.但是,它可能比旧的非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支持它,但我无法测试以前的版本)
标签:javascript,css
来源: https://codeday.me/bug/20190725/1537607.html