我想知道如何在旋转后获取元素的原始尺寸,当我使用 transform: rotate()
并尝试使用 element.getBoundingClientRect()
旋转后获取尺寸时,它返回一个不同的 width 和 heigh,旋转元素后是否可以获得真实尺寸?
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>
答案 0 :(得分:2)
一种选择是使用 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>
答案 1 :(得分:2)
您可以使用 offsetWidth
和 offsetHeight
。这可能比克隆和修改元素更有效。
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())
console.log(div2.offsetWidth);
console.log(div2.offsetHeight);
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>