」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 JavaScript 中取得轉換後元素的準確寬度和高度?

如何在 JavaScript 中取得轉換後元素的準確寬度和高度?

發佈於2024-11-08
瀏覽:654

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

在變換後檢索寬度和高度

當對元素應用諸如旋轉(45deg)之類的變換時,該元素的視覺尺寸改變。但是,JavaScript 中的 width 和 height 屬性仍然反映原始未轉換的尺寸。

解決方案:使用 getBoundingClientRect()

要取得轉換後更新的尺寸,請使用HTMLDOMElement 上的 getBoundingClientRect() 方法。此方法傳回一個包含變換後的高度和寬度的物件。

範例:

// 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;

示範:

造訪此jsFiddle 取得實際範例:https://jsfiddle.net/your_url_here

注意: 此方法將為您提供整個元素的尺寸,包括任何邊框或填充。如果您只需要計算內容尺寸,則應在元素的內容元素上使用 offsetWidth 和 offsetHeight(例如,轉換後的元素中的

)。
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3