我对编程非常陌生,我试图开发一个chrome扩展。我试图操作的网站有一个div
元素,在这个div
中有多个div
,这些div
的数量取决于第一个div
的规模,并且这个比例是由用户拖动的。我的问题是,我需要声明这些变量中的每一个,并让一个变异观察者观察它们的变化。因此,一个用户可能在可拖放窗口中有8个div
,而另一个用户可能在其中有12个div
,所以我希望分别有8个或12个变异观察者。下面是我的代码:
span1 = document.getElementsByClassName("text right")[0];
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
var spantext = span1.textContent;
var spandiv = span1.parentNode;
if (mutation.addedNodes) {
if (spantext > avg) {
spandiv.style.backgroundColor = "#E8E8E8"
spandiv.style.color = "black";
spandiv.style.opacity = "0.7";
}
if (spantext < avg) {
spandiv.style.backgroundColor = "black";
spandiv.style.color = "white";
spandiv.style.opacity = "1";
}
}
})
});
const options = {
childList: true,
subtree: true,
attributes: true,
characterData: true
};
observer.observe(span1, options);
span2 = document.getElementsByClassName("text right")[1];
const observer2 = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
var spantext = span2.textContent;
var spandiv = span2.parentNode;
if (mutation.addedNodes) {
if (spantext > avg) {
spandiv.style.backgroundColor = "#E8E8E8"
spandiv.style.color = "black";
spandiv.style.opacity = "0.7";
}
if (spantext < avg) {
spandiv.style.backgroundColor = "black";
spandiv.style.color = "white";
spandiv.style.opacity = "1";
}
}
})
});
observer2.observe(span2, options);
正如您所看到的,我已经做了2个突变观察者,他们正在观察两个div
,但这是实用的,只有当用户有2个div
在他们的拖放窗口。我真的很感激你的帮助。
发布于 2022-01-14 22:56:02
使用循环将变异观察者添加到所有DIVs。
document.querySelector(".text.right").forEach(span => {
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var spantext = span.textContent;
var spandiv = span.parentNode;
if (mutation.addedNodes) {
if (spantext > avg) {
spandiv.style.backgroundColor = "#E8E8E8"
spandiv.style.color = "black";
spandiv.style.opacity = "0.7";
}
if (spantext < avg) {
spandiv.style.backgroundColor = "black";
spandiv.style.color = "white";
spandiv.style.opacity = "1";
}
}
})
});
const options = {
childList: true,
subtree: true,
attributes: true,
characterData: true
};
observer.observe(span, options);
});
https://stackoverflow.com/questions/70719375
复制相似问题