Sug*_*san 2 javascript mutation-observers
我正在尝试检测元素中CSS属性的更改。我在网上搜索并找到了MutationObserverjavascript API。但是在我的测试脚本中,它无法按预期运行(它不会警告属性名称和属性值)。
var foo = document.getElementById("hideit");
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
alert('mutation.type = ' + mutation.type);
});
});
observer.observe(foo);
observer.disconnect();
$(function() {
$("#clickhere").on("click", function() {
$("#hideit").slideToggle('fase');
});
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<div id="clickhere">click to toggel</div>
<div id="hideit" style="display:none;">this is the content of the hide/show toggle</div>
</body>Run Code Online (Sandbox Code Playgroud)
它显示了一个JavaScript错误
TypeError: Argument 1 of MutationObserver.observe is not an object.
Run Code Online (Sandbox Code Playgroud)
谢谢提前
您的代码中有2个问题:
observer.observe不正确。它应该采用2个参数:Node和MutationObserverInit。在此处查看正确的API 。observer.disconnect();立即致电observe。断开连接停止观察。您的代码正在实际加载DOM之前被执行。由于这个原因,您正在向该observe方法传递null / undefined值。
将您的代码包装在里面:
$( document ).ready(function() {
....
})
Run Code Online (Sandbox Code Playgroud)
同时调用断开连接将阻止它接收任何事件。因此,您不应在致电disconnect后立即致电observe。而且您缺少observe呼叫的参数。
在此处查看工作示例:
https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver#Example_usage