8

I am at the moment working on a little extension to enhance a website namely the google plus post box. I want to move it to the very left of the monitor.

This post box however resets its values every time it is opened.

Basically I would like to kill off that behavior, and thought I could just monitor the element for element.style changes, and overwrite them again. However DOMAttrModified seems not to work for stuff like that

Additionally to that I have found that when the post box is closed it ceases to exist oO?

Maybe someone here has an idea how to tackle this I could of course just loop an operation that sets the style every second or so. but no thanks XD

thanks a lot for helping :)

4

2 回答 2

8

不推荐使用 Mutation 事件,Webkit 浏览器不支持也不支持 DOMAttrModified。改用Mutation Observers。或者,您可以尝试此解决方法

于 2013-06-16T15:34:27.320 回答
4

为了让您快速开始使用Mutation Observer
,这里有一个小的可重用函数

/**
 * 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));
};

要仅跟踪某些元素的属性"style"更改,请使用 likeclass="item"

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

要监视所有属性更改,而不是attributesList使用 Array :

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>

于 2021-03-06T23:55:12.063 回答