2016-08-14 20 views
0

我在幾年前看到過類似的問題,但它們對我沒有用處。我在這裏重複了一些類似的問題,因爲可能會有新的更新。如何在添加,刪除屬性或使用純javascript更改其屬性時獲取事件

我想添加一個屬性時,調用一個函數,刪除文檔中所有元素的元素(或其值改變)。它需要在所有瀏覽器中至少使用chrome和Mozilla Firefox。我想純粹用javascript來實現它。

我試過以下代碼

使用事件監聽器。這適用於Mozilla Firefox,但不適用於Chrome。

document.addEventListener("DOMAttrModified", function(event){ 
console.log('DOMAttrModified invoked'); 
console.log(event); 
}); 

使用觀察者。它不起作用,它使錯誤(WebKitMutationObserver is not defined)錯誤的Firefox。在chrome中,它不會發生任何錯誤,但它不會監聽事件。

var element = document.body, bubbles = false; 
var observer = new WebKitMutationObserver(function (mutations) { 
    mutations.forEach(attrModified); 
}); 
observer.observe(element, { attributes: true, subtree: bubbles }); 

最後,我試了下面。

Element.prototype.setAttribute = function(name, value) { 
    console.log('attribute modified'); 
    console.log(this); 
    console.log(name); 
    console.log(value); 
}; 

很明顯,它的工作在所有瀏覽器,但只能用setAttribute設置屬性值時。例如:var div = document.createElement('div');但不包含div.style = 'color:green';。當設置值如div.style = 'color:green';/div.name = 'somename';時,我也想獲得事件。有什麼辦法可以做到這一點?

回答

0

WebKitMutationObserver是一個臨時的「命名空間」事件,在突變觀察者被明確定義和支持之前。現在,你只需要使用MutationObserver,這是well supported

var element = document.body, bubbles = false; 
 
var observer = new MutationObserver(function (mutations) { 
 
    console.log(mutations); 
 
}); 
 
observer.observe(element, { attributes: true, subtree: bubbles }); 
 
document.body.style.color = "green";

在火狐,Chrome,IE11,和邊緣上述作品。

如果由於某種原因,你需要支持IE9和IE10,他們不得不舊有的支持「突變事件」,並有使用突變事件提供一些突變觀察員的功能過時的瀏覽器墊片。


我也希望像div.style = '顏色:綠色' 設定值時,得到的事件;

這不是設置樣式屬性的有效方法,並且不能可靠地跨瀏覽器工作。要麼div.style.color = "green";(這將離開style單獨的其他方面)或div.setAttribute("style", "color: green");(它將消除其上的任何其他內聯樣式),或至少在某些瀏覽器上,div.style.cssText = "color:green";(它也將消除其上的其他內聯樣式)。

0

我認爲Object.observe()可能是你的情況非常有用:http://www.html5rocks.com/en/tutorials/es7/observe/

並實現類似上述方案, 但Object.observe()不會被棄用和新webstandards

+1

部分不幸的是,它現在不受瀏覽器支持。我用chrome和firefox試了一下,得到'Object.observe不是函數(匿名函數)'。 [說它從firefox文檔中的瀏覽器中刪除](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/observe) –

相關問題