js如何获取元素的宽高
web开发中经常需要获取元素的宽高。
实现方法如下:
js:
var width = getWH(noticeImg, 'width');
var height = getWH(noticeImg, 'height');
var wBh = width/height;
alert("width:"+width);
alert("height"+height);
noticeImg.style.width=(width/3)+ 'px';
noticeImg.style.height=(height/3)+ 'px';
function getStyle(el,name) {
if(window.getComputedStyle) {
return window.getComputedStyle(el, null)[name];
}else{
return el.currentStyle[name];
}
}
function getWH(el, name) {
var val = name === "width" ? el.offsetWidth : el.offsetHeight,
which = name === "width" ? ['Left', 'Right'] : ['Top', 'Bottom'];
// display is none
if(val === 0) {
return 0;
}
for(var i = 0, a; a = which[i++];) {
val -= parseFloat( getStyle(el, "border" + a + "Width") ) || 0;
val -= parseFloat( getStyle(el, "padding" + a) ) || 0;
}
// return val + 'px';
return val;
}