首页  >  文章  >  web前端  >  如何在 JavaScript 中获取转换后元素的准确宽度和高度?

如何在 JavaScript 中获取转换后元素的准确宽度和高度?

Susan Sarandon
Susan Sarandon原创
2024-10-28 03:27:30772浏览

How to Get the Accurate Width and Height of a Transformed Element in JavaScript?

检索变换后的宽度和高度

对元素应用诸如旋转(45deg)之类的变换时,该元素的视觉尺寸改变。然而,JavaScript 中的 width 和 height 属性仍然反映原始未转换的尺寸。

解决方案:使用 getBoundingClientRect()

要获取转换后更新的尺寸,请使用HTMLDOMElement 上的 getBoundingClientRect() 方法。此方法返回一个包含转换后的高度和宽度的对象。

示例:

<code class="javascript">// Get the element
const element = document.querySelector('.transformed');

// Calculate the rotated dimensions
const rect = element.getBoundingClientRect();

// Access the rotated width and height
const rotatedWidth = rect.width;
const rotatedHeight = rect.height;</code>

演示:

访问这个 jsFiddle 是一个实际示例:https://jsfiddle.net/your_url_here

注意: 此方法将为您提供整个元素的尺寸,包括任何边框或填充。如果您只需要计算内容尺寸,则应在元素的内容元素上使用 offsetWidth 和 offsetHeight(例如,转换后的元素中的

)。

以上是如何在 JavaScript 中获取转换后元素的准确宽度和高度?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn