分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

JS获取盒模型对应的宽高

发布时间:2023-09-06 02:33责任编辑:白小东关键词:暂无标签

## 获取内联样式宽高

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved