作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
有一个具有特定 HTML 元素的网站,如果我理解正确的话,它在 DOMContentLoaded
处具有相同的类。事件和load
事件,但在 load
之后的某个时间发生事件时,此类(可能还有 ID 和 HTML 属性)会发生更改。
我想从该元素存在于 DOM 上的第一刻起就“观察”它,以便自动跟踪其 HTML 可能发生的任何更改。
有没有办法通过 CSS 选择器观察元素的 DOM 突变?如果可以,该怎么做?
我问这个问题是假设我正确理解了 JavaScript 中的“观察”概念。
最佳答案
Is there a way to observe a DOM mutation of an element by a CSS selector...
有点。您可以使用 mutation observer 观察元素及其后代元素中的所有修改。 ,您可以使用matches
方法对您看到的添加或修改的元素进行检查,以查看它们是否与给定的 CSS 选择器匹配(或在您正在观看的容器上使用 querySelector
)。
通过结合使用突变观察器和matches
/querySelector(All)
,您可以看到您需要查看的任何更改。
// Get the container
let container = document.getElementById("container");
// The selector we're interested in
let selector = "div.foo";
// Set up a mutation observer
let observer = new MutationObserver(records => {
// A mutation occurred within the container.
// `records` contains the information about the mutation(s)
// If you're looking to see if a new element matching the selector
// was *added*, you can loop through the added nodes (if any)
for (const record of records) {
for (const added of record.addedNodes) {
if (added.nodeType === Node.ELEMENT_NODE && added.matches(selector)) {
console.log("Matching element added: " + added.textContent);
}
}
}
// If you're looking to see if an element *changed* to match the
// selector, you can look at the target of each record
for (const {target} of records) {
if (target.nodeType === Node.ELEMENT_NODE && target.matches(selector)) {
console.log("Element changed to match: " + target.textContent);
}
}
// Or alternatively ignore the records and *why* an element now matches,
// and just see if any does.
const found = container.querySelectorAll(selector);
if (found.length) {
console.log("Matching elements found: " + found.length);
for (const {textContent} of found) {
console.log("Matching element found: " + textContent);
}
}
});
observer.observe(container, {
// Tweak what you're looking for depending on what change you want to find.
childList: true,
subtree: true,
attributes: true
});
// Add five div elements; the fourth will have the
// class we're interested in.
let counter = 0;
let timer = setInterval(() => {
const div = document.createElement("div");
++counter;
div.textContent = "Div #" + counter;
if (counter === 4) {
div.className = "foo";
}
console.log("Adding div: " + div.textContent);
container.appendChild(div);
if (counter === 5) {
clearInterval(timer);
}
}, 200);
// After 1200ms, *change* one of the divs to match the selector
setTimeout(() => {
const div = container.querySelector("div:not(.foo)");
console.log("Changing element to match: " + div.textContent);
div.className = "foo";
}, 1200);
<div id="container">
This is the container.
</div>
当然,您需要调整传递给观察者的选项以及观察者回调中的代码以匹配您的场景。 :-)
关于javascript - 有没有办法通过 CSS 选择器观察元素的 DOM 突变?如果可以,该怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60344524/
我是一名优秀的程序员,十分优秀!