Joã*_*ski 5 html javascript css
我想知道如何在旋转后获得元素的原始尺寸,当我使用transform: rotate()并尝试在旋转后获得尺寸时,使用element.getBoundingClientRect()它返回不同的宽度和高度,是否有可能在旋转后获得真实尺寸元素?
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())Run Code Online (Sandbox Code Playgroud)
div#one {
width: 50px;
height: 80px;
background-color: red;
}
div#two {
width: 50px;
height: 80px;
background-color: red;
transform: rotate(35deg);
}Run Code Online (Sandbox Code Playgroud)
<div id="one"></div>
<br/>
<div id="two"></div>Run Code Online (Sandbox Code Playgroud)
一种选择是克隆第二个 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());Run Code Online (Sandbox Code Playgroud)
div#one {
width: 50px;
height: 80px;
background-color: red;
}
div#two {
width: 50px;
height: 80px;
background-color: red;
transform: rotate(35deg);
}Run Code Online (Sandbox Code Playgroud)
<div id="one"></div>
<br/>
<div id="two"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55 次 |
| 最近记录: |