JavaScript获取元素的宽高

2,443 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

JavaScript进行页面编辑时,我们经常会遇到获取页面元素宽高的情况,只不过由于太过常态化了,所以常常被我们直接忽视掉。

有关于获取元素宽高的方式有很多种,根据不同的使用情况,可以选择最适合自己的方式

jQuery

如果是使用jQuery,可以直接使用$('元素').width()$('元素').height()的方式进行获取。

console.log(`${$('#app').width()} + ${$('#app').height()}`);

image.png


JavaScript原生方法

style

如果使用了原生的JavaScript,可以看是否在style属性中设置值来进行获取,方式:element.style.widthelement.style.height

document.getElementById('app').style.width;
document.getElementById('app').style.height;

但是当style中并没有设置,只是在CSS中通过类或ID选择器进行设置,那么element.style的方式获取到的宽高就是空的。


getComputedStyle()

这里的getComputedStyle方法并不是跟随在element之后的,而是window上面的方法。

Window.getComputedStyle()方法返回一个对象,该对象在应用活动样式表并解析这些值可能包含的任何基本计算后报告元素的所有CSS属性的值。 私有的CSS属性值可以通过对象提供的API或通过简单地使用CSS属性名称进行索引来访问。

使用方式:window.getComputedStyle(element).width或者window.getComputedStyle(element).getPropertyValue(width)

let dom = document.getElementById('app');
console.log(`${window.getComputedStyle(dom).width} + ${window.getComputedStyle(dom).height}`);
console.log(`${window.getComputedStyle(dom).getPropertyValue('width')} + ${window.getComputedStyle(dom).getPropertyValue('height')}`);

这里需要注意一点,获取到的宽高后面会带上px;并且在IE9以下的版本中,是不支持getComputedStyle的。

image.png


getBoundingClientRect

Element.getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置。

这种方式可以在element后面直接使用,并且返回的也是直接number类型的数值,后面不带px。并且可以支持到IE4

console.log(`getBoundingClientRect: ${dom.getBoundingClientRect().width} + ${dom.getBoundingClientRect().height}`);

image.png


一般来说,JavaScript获取元素宽高后,会进行操作修改,这里就会涉及到重排和重绘了,一般为了性能考虑,获取和改变元素大小的操作最好不要太频繁。

注意: 这里使用getBoundingClientRectgetComputedStyle也会导致重排。