首页 > 解决方案 > 旋转后如何获得元素的真实宽度和高度?

问题描述

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

标签: javascripthtmlcss

解决方案


一种选择是克隆第二个 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>


推荐阅读