ResizeObserver: phương thức unobserve()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2020.

Phương thức unobserve() của giao diện ResizeObserver kết thúc việc theo dõi một Element hoặc SVGElement được chỉ định.

Cú pháp

js
unobserve(target)

Tham số

target

Tham chiếu đến một Element hoặc SVGElement sẽ ngừng được theo dõi.

Giá trị trả về

Không có (undefined).

Ngoại lệ

Không có.

Ví dụ

Đoạn mã sau được lấy từ ví dụ resize-observer-text.html (xem mã nguồn):

js
const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    if (entry.contentBoxSize) {
      // Kiểm tra chrome vì đang dùng một mảng không chuẩn
      if (entry.contentBoxSize[0]) {
        h1Elem.style.fontSize = `${Math.max(
          1.5,
          entry.contentBoxSize[0].inlineSize / 200,
        )}rem`;
        pElem.style.fontSize = `${Math.max(
          1,
          entry.contentBoxSize[0].inlineSize / 600,
        )}rem`;
      } else {
        h1Elem.style.fontSize = `${Math.max(
          1.5,
          entry.contentBoxSize.inlineSize / 200,
        )}rem`;
        pElem.style.fontSize = `${Math.max(
          1,
          entry.contentBoxSize.inlineSize / 600,
        )}rem`;
      }
    } else {
      h1Elem.style.fontSize = `${Math.max(
        1.5,
        entry.contentRect.width / 200,
      )}rem`;
      pElem.style.fontSize = `${Math.max(1, entry.contentRect.width / 600)}rem`;
    }
  }
  console.log("Kích thước đã thay đổi");
});

resizeObserver.observe(divElem);

checkbox.addEventListener("change", () => {
  if (checkbox.checked) {
    resizeObserver.observe(divElem);
  } else {
    resizeObserver.unobserve(divElem);
  }
});

Thông số kỹ thuật

Specification
Resize Observer
# dom-resizeobserver-unobserve

Tương thích trình duyệt