js获取元素高度怎么写呢?

JavaScript016

js获取元素高度怎么写呢?,第1张

document.getElementById("div").offsetHeight;这个是获取元素高度。

getElementById("div") 里的div要换成自己的id值就可以了

(1)dom.style.width/height 获取dom元素内联样式中设定的width,height

(2)dom.currentStyle.width/height 获取dom元素渲染后的width,height,只支持IE

(3)window.getComputedStyle(dom).width/height 浏览器渲染后的元素宽,兼容性更好

(4)dom.getBoundingClientRect().width/height/left/top/right/ 计算一个元素的绝对位置(相对于视窗左上角),它能拿到元素的left、top、right、bottom、width、height

Element.getBoundingClientRect() - Web API 接口参考 | MDN

// html

<div class="a"></div>

// js

document.querySelector('.a').getBoundingClientRect()

//返回 x,y width,height,top,left,right,bottom等元素的信息需要注意的是该方法

需要处理浏览器兼容