码迷,mamicode.com
首页 > Web开发 > 详细

JS获取盒模型对应的宽高

时间:2019-02-14 23:56:52      阅读:325      评论:0      收藏:0      [点我收藏+]

标签:func   width   test   return   put   无法   参数   let   turn   

## 获取内联样式宽高

只能获取内联设置的样式,在style或者.css文件中设置的无法获取

1 let div = document.querySelect(‘.test‘);
2 let width = div.style.width
3 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获取盒模型对应的宽高

标签:func   width   test   return   put   无法   参数   let   turn   

原文地址:https://www.cnblogs.com/hughes5135/p/10381260.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!