• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
骑着小毛驴过冬的八阿哥
博客园    首页    新随笔    联系   管理    订阅  订阅

JS获取盒模型对应的宽高

## 获取内联样式宽高

只能获取内联设置的样式,在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();

 

 

posted @ 2019-02-14 23:20  浅草马甲  阅读(569)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3