blo*_*ead 21 dom webkit mutation-events
我需要利用这个DOM事件.IE有onpropertychange,这也是我需要它做的事情.但是,Webkit似乎不支持此事件.有没有我可以使用的替代方案?
dal*_*ege 24
虽然Chrome不会调度DOMAttrModified
事件,但自2011年以来支持的轻量级变异观察器就越多,这些也适用于属性更改.
以下是文档正文的示例:
var element = document.body, bubbles = false;
var observer = new WebKitMutationObserver(function (mutations) {
mutations.forEach(attrModified);
});
observer.observe(element, { attributes: true, subtree: bubbles });
function attrModified(mutation) {
var name = mutation.attributeName,
newValue = mutation.target.getAttribute(name),
oldValue = mutation.oldValue;
console.log(name, newValue, oldValue);
}
Run Code Online (Sandbox Code Playgroud)
对于简单的属性更改,console.log
语句将打印:
<body color="black">
<script type="text/html">
document.body.setAttribute("color", "red");
</script>
</body>
Run Code Online (Sandbox Code Playgroud)
安慰:
> color red black
Sea*_*gan 13
如果您对仅仅检测调用setAttribute()
(而不是监视所有属性修改)感到满意,那么您可以在以下所有元素上覆盖该方法:
Element.prototype._setAttribute = Element.prototype.setAttribute
Element.prototype.setAttribute = function(name, val) {
var e = document.createEvent("MutationEvents");
var prev = this.getAttribute(name);
this._setAttribute(name, val);
e.initMutationEvent("DOMAttrModified", true, true, null, prev, val, name, 2);
this.dispatchEvent(e);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19519 次 |
最近记录: |