2016-08-14 53 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) –

相关问题