2012-10-09 4 views
0

왼쪽 CSS 위치에 따라 dom 요소의 순서를 변경하려면 어떻게해야합니까?CSS 위치 별 dom의 요소 순서 변경

저는 left 값이 10, 20, 30 %이고, position: absolute 인 3 개의 요소가 있습니다.

DOM의 경우 DOM은 20, 10, 30이며, left 속성 (10, 20, 30)에 따라 오름차순으로 주문하고 싶습니다.

세 가지 요소는 parent

답변

0

정렬 할 수 있도록 자식 요소를 배열로 반복해야합니다. 그런 다음 올바른 순서로 자식을 다시 연결해야합니다. 이 작업은 jQuery없이 순수 자바 스크립트로 수행 할 수 있습니다.

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 요소를 통해 루프, 배열에 넣어 ID와 div 내부에 있습니다. 그런 다음 원하는 속성 (이 경우 window.getComputedStyle(elem)['left'])으로 배열을 정렬 한 다음 배열에서 지시하는 순서대로 요소를 다시 삽입하십시오.