gpt4 book ai didi

javascript - 旋转后如何获得元素的真实宽度和高度?

转载 作者:行者123 更新时间:2023-12-03 16:30:39 25 4
gpt4 key购买 nike

我想知道当我使用 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())
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>

最佳答案

一种选择是使用 cloneNode 克隆第二个 div。然后删除 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>

关于javascript - 旋转后如何获得元素的真实宽度和高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67441092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com