【问题标题】:Mutation Observer is undefined突变观察者未定义
【发布时间】:2013-12-21 09:52: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

我做错了吗? 附加信息: 页面是一个 netsuite 页面,运行 jQuery 1.7.2(如果重要的话)

【问题讨论】:

  • 您确定浏览器运行在 IE11 标准模式下吗?
  • “自从 IE 不再支持控制台” 从什么时候开始? (按 F12 和 console.log 将起作用)
  • 该页面在 IE-9 兼容模式下自动运行,因为 Netsuite 设置了该模式,这显然也是我永远无法使用 console.log() 的原因......
  • 这可以解释为什么IE11中添加的方法对您不可用。
  • 确实将其放入答案中并将其标记为解决方案,感谢您告知我一些让我很沮丧的事情。

标签: javascript jquery internet-explorer-11 netsuite mutation-observers


【解决方案1】:

如果您需要检测 IE10+(以及其他尚不支持 MutationObserver 的浏览器)中的 DOM 插入,您可以使用基于侦听 animationstart 事件的技巧来为不支持的属性设置动画。影响节点的外观。

该技术是由 Daniel Buchner 发现的,你可以看到它描述了它this post by 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
});

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 正如评论一样,Netsuite 自动在 ie-9 兼容模式下运行,这正是导致问题的原因。
    猜你喜欢
    • 1970-01-01
    • 2012-05-20
    • 2018-06-15
    • 2015-09-05
    • 2017-03-04
    • 2020-01-30
    • 2021-09-23
    • 2014-08-12
    • 1970-01-01
    相关资源
    最近更新 更多