## 获取内联样式宽高
只能获取内联设置的样式,在style或者.css文件中设置的无法获取
1 let div = document.querySelect(‘.test‘);2 let width = div.style.width3 let height = div.style.height
## currentStyle和getComputedStyle获取所有样式
两者只能获取样式,不能设置样式
let div = document.querySelect(‘.test‘);let width;if (div.currentStyle) { ?width = div.currentStyle.width;} else { ?width = window.getComputedStyle(div, null).width; ??// width = window.getComputedStyle(div, null)[‘width‘]; ??// 第二个参数可选,省略或者null}
针对获取任意样式,可做兼容性处理方法:
1 function getStyle(element, attr) {2 ??if(element.currentStyle) {3 ?????return element.currentStyle[attr];4 ??} else {5 ?????return getComputedStyle(element, false)[attr];6 ??}7 }
至于 getBoundingClientRect()是获取相对于视窗位置的集合, 可对应获取宽高,大小, 位置。
1 let div = document.querySelector(‘.test‘);2 let rectObject = div.getBoundingClientRect();
JS获取盒模型对应的宽高
原文地址:https://www.cnblogs.com/hughes5135/p/10381260.html