<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>~'"#@!#@$!</title> </head> <body style="height: 600vh"> <div id="div" style="width: 300px; height: 300px; background: #c7e"></div> <button id="btn1">测试</button> <script> const div = document.querySelector("#div"); const btn1 = document.querySelector("#btn1"); // 监听元素改变 let flag = true; btn1.addEventListener("click", () => { if (flag) { div.style.height = "200px"; flag = false; const el = document.createElement("span"); el.innerText = "hello world"; div.appendChild(el); } else { div.style.height = "300px"; flag = true; div.removeChild(document.querySelector("div span")); } }); const observerOptions = { childList: true, // 观察目标子节点的变化,是否有添加或者删除 attributes: true, // 观察属性变动 subtree: true, // 观察后代节点,默认为 false }; function callback(a, s) { console.log(a, s); } const observer = new MutationObserver(callback); observer.observe(div, observerOptions); // 监听元素进入可视区域 const cb = (entries) => { // 显示为true, 隐藏为false console.log(entries[0].isIntersecting); }; const intersectionObserver = new IntersectionObserver(cb); intersectionObserver.observe(div); </script> </body> </html>
MutationObserver 用于监听元素的自身属性内容的一些变化
IntersectionObserver 用于监听元素的显示与隐藏(虚拟滚动原理)
标签:const,javascrpt,flag,API,div,document,true,监听 From: https://www.cnblogs.com/fmg0224/p/16951517.html