DIV 元素中的尺寸變化檢測
檢測DIV 元素尺寸的變化,尤其是在視窗大小調整期間,可能是一項很有價值的功能在某些情況下。本文探討如何使用 Resize Observer API 來實現此目的。
jQuery 調整大小事件處理程序(如提供的 HTML 程式碼所示)不適合此目的。 Resize Observer API 提供了一種標準化且更有效的方法來偵聽 DOM 元素中的尺寸變化。
使用Resize Observer API
偵測DIV 中的尺寸變化使用Resize Observer API,請依照下列步驟操作:
const observer = new ResizeObserver(callback);
function callback(entries) { // Check if the entry pertains to the target DIV const targetIndex = entries.findIndex((entry) => entry.target === targetDiv); if (targetIndex < 0) { return; } // Update the dimensions based on the entry's contentRect const { width, height } = entries[targetIndex].contentRect; targetDiv.style.width = `${width}px`; targetDiv.style.height = `${height}px`; }
observer.observe(targetDiv);
<script src="https://cdn.jsdelivr.net/npm/resize-observer-polyfill@1.5.1/dist/ResizeObserver.min.js"></script>
範例程式碼
以下程式碼片段提供了使用調整大小的實際範例Observer API:
<div>透過利用Resize Observer API,您可以有效地檢測DIV 元素中的尺寸變化,從而使您能夠在Web應用程式中做出相應的回應。
以上是如何高效率檢測DIV元素尺寸變化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!