最新的 Safari (6.0) 确实包括WebKitMutationObserver
. 对于较旧的 Safari,以下是我们使用的一些代码,DOMAttrModified
当您使用setAttribute
或removeAttribute
更改属性时会伪造事件。请注意,如果浏览器本身在内部更改属性,这将不起作用。
var win = window;
var doc = win.document;
var attrModifiedWorks = false;
var listener = function () { attrModifiedWorks = true; };
doc.documentElement.addEventListener("DOMAttrModified", listener, false);
doc.documentElement.setAttribute("___TEST___", true);
doc.documentElement.removeAttribute("___TEST___", true);
doc.documentElement.removeEventListener("DOMAttrModified", listener, false);
if (!attrModifiedWorks)
{
This.DOMAttrModifiedUnsupported = true;
win.HTMLElement.prototype.__setAttribute = win.HTMLElement.prototype.setAttribute;
win.HTMLElement.prototype.setAttribute = function fixDOMAttrModifiedSetAttr (attrName, newVal)
{
var prevVal = this.getAttribute(attrName);
this.__setAttribute(attrName, newVal);
newVal = this.getAttribute(attrName);
if (newVal != prevVal)
{
var evt = doc.createEvent("MutationEvent");
evt.initMutationEvent
( "DOMAttrModified"
, true
, false
, this
, prevVal || ""
, newVal || ""
, attrName
, (prevVal == null) ? win.MutationEvent.ADDITION : win.MutationEvent.MODIFICATION
);
this.dispatchEvent(evt);
}
}
win.HTMLElement.prototype.__removeAttribute = win.HTMLElement.prototype.removeAttribute;
win.HTMLElement.prototype.removeAttribute = function fixDOMAttrModifiedRemoveAttr (attrName)
{
var prevVal = this.getAttribute(attrName);
this.__removeAttribute(attrName);
var evt = doc.createEvent("MutationEvent");
evt.initMutationEvent("DOMAttrModified", true, false, this, prevVal, "", attrName, win.MutationEvent.REMOVAL);
this.dispatchEvent(evt);
}
}
}