跳到主要内容

观察者 API

MutationObserver 如何监控 DOM 变化?​

  • 语义: 观察节点树的变动, 变动记录在微任务中批量回调;
  • API:
成员作用
new MutationObserver(callback)创建观察者, 回调参数为 MutationRecord[] 与观察者本身
observer.observe(target, options?)开始观察
observer.disconnect()停止观察, 之后可重新 observe
observer.takeRecords()取出已检测但尚未处理的记录
  • MutationRecord: 单次变动的元数据; MutationObserverInit: 观察选项 (如 { attributes: true });
const observer = new MutationObserver((records) => console.log(records.map((r) => r.target)));
observer.observe(childA, { attributes: true });
observer.disconnect();

IntersectionObserver 如何监听交叉状态?​

  • 语义: 异步观察目标元素与视口 (或指定根元素) 的交叉状态, 常用于懒加载与曝光统计;
  • API:
成员作用
new IntersectionObserver(callback, options?)创建观察者, 回调参数为 IntersectionObserverEntry[]
observer.observe(target)开始观察指定元素
observer.unobserve(target)停止观察指定元素
observer.disconnect()停止观察全部元素
observer.takeRecords()取出未处理的交叉记录
  • IntersectionObserverEntry: 目标元素的交叉元数据, 其中 intersectionRatio 表示交叉比例;
  • IntersectionObserverInit: 配置根元素与阈值;
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.intersectionRatio > 0) {
// 进入视口
}
});
});
observer.observe(target);