javascript - 旋转后如何获得元素的真实宽度和高度?
问题描述
我想知道如何在旋转元素后获得元素的原始尺寸,当我使用transform: rotate()
并尝试在旋转后获得尺寸时,使用element.getBoundingClientRect()
它返回不同的宽度和高度,是否有可能在旋转后获得真实尺寸 a元素?
let div1 = document.getElementById('one')
let div2 = document.getElementById('two')
// Here the width and height is 50 and 80
console.log(div1.getBoundingClientRect())
// Here because i used transform rotate the width is 86 and height 94
console.log(div2.getBoundingClientRect())
div#one {
width: 50px;
height: 80px;
background-color: red;
}
div#two {
width: 50px;
height: 80px;
background-color: red;
transform: rotate(35deg);
}
<div id="one"></div>
<br/>
<div id="two"></div>
解决方案
一种选择是克隆第二个 div,cloneNode
然后删除tranform
样式以获取其原始尺寸,请参阅片段。
let div1 = document.getElementById('one');
let div2 = document.getElementById('two');
//clone the rotated div and then remove the transform style
//this will give you it's original dimensions
let div3 = div2.cloneNode(false);
div3.style.transform = "none";
//hide the clone
div3.style.visibility = "hidden";
//append to the body
document.body.append(div3);
console.log(div3.getBoundingClientRect());
//remove clone from the DOM
div3.remove();
// Here the width and height is 50 and 80
console.log(div1.getBoundingClientRect());
// Here because i used transform rotate the width is 86 and height 94
console.log(div2.getBoundingClientRect());
div#one {
width: 50px;
height: 80px;
background-color: red;
}
div#two {
width: 50px;
height: 80px;
background-color: red;
transform: rotate(35deg);
}
<div id="one"></div>
<br/>
<div id="two"></div>
推荐阅读
- python - docs.python.org 与代码不同
- google-apps-script - 检查谷歌工作表中所有工作表之间的重复项
- javascript - javascript > Kendo 网格 > 动态列过滤不起作用
- apache - 配置 apache2 和 host 以使用 nginx 将流量传递到 docker 容器
- apollo-client - 如何让所有可见的 Vue 组件重新获取它们的 Apollo 查询?
- swift - 如何在 Swift 中集成套接字 I/O?
- vba - Excel SQL 在 PowerPoint 中工作以选择和调整图片大小
- html - 输入模式不匹配,而它似乎在 regex101 中工作
- aem - 如何在给定路径下和仅在 AEM 6 中使用查询生成器激活的页面下执行全文搜索?
- python - python脚本中的命令行给出语法错误