[英]reorder elements in the dom by css position
如何根據左CSS位置重新排列dom元素?
我有3個元素,其left
值分別為10%,20%和30%, position: absolute
。
在DOM中,它們的順序為20, 10, 30
但我想根據left
屬性( 10, 20, 30
)將它們升序。
所有這三個元素都在具有id parent
的div
內
基本上,遍歷要修改的DOM元素,然后將它們放入數組中。 然后根據所需的屬性對數組進行排序(在本例中為window.getComputedStyle(elem)['left']
),然后按照數組告訴您的順序重新插入元素。
您需要將子元素作為數組循環遍歷,以便可以對它們進行排序,然后需要以正確的順序重新附加子元素。 這可以在沒有jQuery的純JavaScript中完成:
var parent = document.getElemntById(parent),
children = [];
// loop through the child nodes, add them to your array
// and remove them from the parent
for (var i = parent.childNodes.length-1; i >= 0; i--) {
children.push(parent.childNodes[i]);
parent.removeChild(parent.childNodes[i]);
}
// sort them based on the left property
children.sort(function(a,b){
return window.getComputedStyle(a)['left'] - window.getComputedStyle(b)['left'];
});
// add them back to the parent in order
for (var i in children) {
parent.appendChild(children[i]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.