检测元素.Javascript会改变样式

Detect Element.Style changes with Javascript

本文关键字:改变 样式 Javascript 元素 检测      更新时间:2023-09-26

我现在正在做一个小小的扩展来增强一个网站,即google +邮箱。我想把它移到显示器的最左边。

这个邮箱在每次打开时都会重置它的值。

基本上,我想要消除这种行为,并且认为我可以逐个元素地监视元素。样式更改,并再次覆盖它们。然而,DOMAttrModified似乎不适用于这样的东西

除此之外,我还发现当邮箱关闭时,它就不存在了oO?

也许有人有办法解决这个问题当然,我可以循环一个操作,每秒设置一次样式。但是没有,谢谢XD

非常感谢你的帮助

不支持突变事件,webkit浏览器不支持DOMAttrModified。使用突变观察者代替。或者,您可以尝试以下方法:

让您快速开始使用突变观察者
这是一个小的可重用函数

/**
 * Mutation Observer Helper function
 * //developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe
 * @param {string} sel The DOM selector to watch 
 * @param {object} opt MutationObserver options 
 * @param {function} cb Pass Mutation object to a callback function
 */
const Observe = (sel, opt, cb) => {
  const Obs = new MutationObserver((m) => [...m].forEach(cb));
  document.querySelectorAll(sel).forEach(el => Obs.observe(el, opt));
};

要在某些class="item"元素上只跟踪属性"style"的变化,使用:

Observe(".item", {
  attributesList: ["style"], // Only the "style" attribute
  attributeOldValue: true,   // Report also the oldValue
}, (m) => {
  console.log(m);            // Mutation object
});

查看所有属性的变化,而不是使用attributesList数组:

attributes: true

如果需要,这里有一个例子:

/**
 * Mutation Observer Helper function
 * //developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe
 * @param {string} sel The DOM selector to watch 
 * @param {object} opt MutationObserver options 
 * @param {function} cb Pass Mutation object to a callback function
 */
const Observe = (sel, opt, cb) => {
  const Obs = new MutationObserver((m) => [...m].forEach(cb));
  document.querySelectorAll(sel).forEach(el => Obs.observe(el, opt));
};
// DEMO TIME:
Observe("#test", {
  attributesList: ["style"], 
  attributeOldValue: true,
}, (m) => {
  console.log(`
    Old value: ${m.oldValue}
    New value: ${m.target.getAttribute(m.attributeName)}
  `);
});
const EL_test = document.querySelector("#test");
EL_test.addEventListener("input", () => EL_test.style.cssText = EL_test.value);
EL_test.style.cssText = EL_test.value;
* {margin:0;}
textarea {width: 60%;height: 50px;}
<textarea id="test">
background: #0bf;
color: #000;
</textarea>