簡體   English   中英

使用 Javascript 檢測 Element.Style 更改

[英]Detect Element.Style changes with Javascript

我目前正在做一個小擴展來增強一個網站,即 google plus 郵箱。 我想把它移到顯示器的最左邊。

但是,此郵箱每次打開時都會重置其值。

基本上我想終止這種行為,並認為我可以只監視 element.style 更改的元素,然后再次覆蓋它們。 然而 DOMAttrModified 似乎不適用於這樣的東西

除此之外,我發現當郵箱關閉時它就不復存在了oO?

也許這里有人知道如何解決這個問題,我當然可以循環一個操作,每隔一秒左右設置一次樣式。 但不,謝謝XD

非常感謝您的幫助:)

不推薦使用 Mutation 事件,Webkit 瀏覽器支持也不支持 DOMAttrModified。 改用Mutation Observers 或者,您可以嘗試此解決方法

讓您快速開始使用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));
};

要僅跟蹤某些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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM