2012-10-09 29 views
0

如何根據剩餘的css位置重新排列dom元素?通過css位置重新排列dom中的元素

我有3個元素,其中left的值爲10,20和30%,而position: absolute

在DOM中,它們的順序是20, 10, 30,但我想按照left屬性(10, 20, 30)對它們進行升序排列。

所有三個要素是一個div內部ID爲parent

回答

0

您需要循環遍歷子元素作爲數組,以便可以對它們進行排序,然後您需要按照正確的順序重新附加子級。這可以在沒有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]); 
} 
0

基本上,遍歷你要修改的DOM元素,把它們放在一個陣列。然後按您想要的屬性(在本例中爲window.getComputedStyle(elem)['left'])對數組進行排序,然後按陣列告訴您的順序重新插入元素。