2012-10-09 32 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'])对数组进行排序,然后按阵列告诉您的顺序重新插入元素。