突变观察者尚未定义

Mutation Observer is undefined

本文关键字:未定义 观察者 突变      更新时间:2024-03-03

我正在尝试修复并解决我的代码问题。我最初使用DOMNodeRemoved和DOMNodeInserted来关注我正在处理的页面中的元素。它们工作得很好,但在IE中不起作用。所以我开始尝试使用MutationObserver。

这是我在onPageInit上调用的代码(回调写入控制台,但由于IE不再支持控制台,我禁用了它):

var callback = function(allmutations){
    allmutations.map( function(mr){
        var mt = 'Mutation type: ' + mr.type;  // log the type of mutation
        mt += 'Mutation target: ' + mr.target; // log the node affected.
        //console.log( mt );
    })
}
mo = new MutationObserver(callback),
options = {
    // required, and observes additions or deletion of child nodes.
    'childList': true, 
    // observes the addition or deletion of "grandchild" nodes.
    'subtree': true
}
alert('its alive');
mo.observe(document.body, options);

它在chrome中运行良好,但由于某种原因,在IE中表现平平。我在加载页面时收到一个消息框,上面写着:

An unexpected error occurred in a script running on this page.
onPageInit(pageInit)
scriptname
JS_EXCEPTION
TypeError 'MutationObserver' is undefined

我做错什么了吗?其他信息:页面是一个网络套件页面,运行jQuery 1.7.2(如果重要的话)

如果您需要在IE10+(以及其他还不支持MutationObserver的浏览器)中检测DOM插入,您可以使用一个基于侦听animationstart事件的技巧来制作CSS动画,该动画可以动画化不会影响节点外观的属性。

这项技术是由Daniel Buchner发现的,你可以看到它是由David Walsh 在这篇文章中描述的

使其工作所需的代码如下:

@keyframes animationName{ 
    from { outline: 1px solid transparent } 
    to { outline: 0px solid transparent } 
}
* { 
    animation-duration: 0.001s; 
    animation-name: animationName;
}

document.addEventListener('animationstart', insertionHandler, false);

使用所有前缀和事件侦听器名称,跨浏览器工作所需的设置非常复杂。将为每个新节点调用处理程序,并且很难选择要设置动画的属性。

这就是为什么我把它包在图书馆里,使它易于使用:https://github.com/naugtur/insertionQuery

下面是一个简单的用法示例:

insertionQ('selector').every(function(element){
    //callback on every new element
});

该方法是在IE11中添加的,因此,如果浏览器以兼容模式运行IE11以外的任何内容,则该方法将不可用。

http://msdn.microsoft.com/en-us/library/ie/dn265034(v=vs.85).aspx