如何在旋转元素后获取其实际宽度和高度?

7

我想知道如何在旋转元素时获取其原始尺寸,当我使用 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>


2
你可以在旋转之前保存元素的高度,并将其用作参考。 - Prosy Arceno
2
getComputedStyle(element)["height"]getComputedStyle(element)["width"] 是一个潜在的选项。 - Nisala
这回答您的问题吗?如何在Javascript中测量旋转元素的宽度和高度? - Heretic Monkey
2个回答

3

您可以使用offsetWidthoffsetHeight。这可能比克隆和修改元素更有效。

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>


1
谢谢你的回答,它也有效,但有时使用getBoundingClientRect更好,因为它在元素调整大小时返回实际尺寸,所以我不使用offsetWidthclientWidth - João Hamerski
1
@Nisala 我给了你一个赞。我更新了我的答案,看起来可以工作,但使用了更多的资源。 - Ryan Wilson
我的意思是,如果您在元素中使用 transform: scale(1.3),那么区别就在于如果您使用 getBoundingClientRect().width 它将返回真实尺寸,但如果您使用 offset.width 它将返回不考虑 transform: scale() 属性的尺寸。 - João Hamerski

1

一种选择是使用 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>


出于某种原因,这给了我宽度和高度为0。 - Nisala
谢谢,我在这里测试了一下,你的想法完美地奏效了,我之前没有意识到。但是你的代码出了些问题,无法正常工作。 - João Hamerski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接