检测DOM元素顺序的变化 [英] Detect changes in DOM elements order
问题描述
我有以下代码:
<div>
<span>Random text</span>
<span style="color: red">Random text</span>
</div>
并使用代码,我有50%的机会更改div内的元素的顺序。$ {
$ b
and, using code, I have a 50% chance of changing the order of the elements inside the div.
$(document).ready(function() {
var initial = $("div"); //This might not be ok
if (new Date() % 2) //50% chance to randomize order
randomizeOrder();
var after = $("div"); //Also this might not be ok
//Detect if the order of spans changed
if (after != initial) //Definitely won't work
console.log("Order changed");
})
function randomizeOrder() {
var lastElement = $("div span").last();
$(lastElement).insertBefore($("div span").first());
}
此示例过于简单。订购是由用户完成的,使用第三方库,不会告诉我,如果订单实际上改变,只是告诉我什么时候开始&完成。
This example is oversimplified. The ordering is done by the user using a 3rd party library which won't tell me if the order actually changed, just tell me when it started & finished.
如何检测DOM元素的顺序是否实际改变?我内部的信息不能被使用,因为它可以是完全一样的,如在例子中。
How can I detect if the order of the DOM elements actually changed? The information I have inside them cannot be used, as it can be exactly the same, as in the example.
推荐答案
如果要检查DOM中的更改,可以使用 MutationObserver
:
If you want to check for changes in the DOM you can use the MutationObserver
:
$(document).ready(function() {
var initial = $("div"); //This might not be ok
if (new Date() % 2) {
randomizeOrder();
}
});
function randomizeOrder() {
var lastElement = $("div span").last();
$(lastElement).insertBefore($("div span").first());
}
var target = document.getElementById('id1');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
var changed = false;
mutations.forEach(function(mutation) {
// You can check the actual changes here
});
console.log('Dom Changed');
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1">
<span>Random text</span>
<span style="color: red">Random text</span>
</div>
MutationObserver
使您能够检查特定元素中的DOM更改,而不需要更改DOM的代码。
The MutationObserver
gives you the ability to check for DOM changes in a specific element, without any requirement regarding the code the changes the DOM.
这篇关于检测DOM元素顺序的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!