2011-12-16 3 views
0

아이콘을 클릭하여 상자 모양의 창을 만들 수 있기를 원합니다. 하나를 만들고 다시 클릭하면 다른 하나가 만들어집니다. 내 코드로 여러 상자를 만들 수 있지만 inner-div는 첫 번째 열린 창에서만 만들어집니다. 그 이유는 여러 개의 상자가 만들어지면 div가 id를 가지게되므로 당연히 올바른 방법이 아니기 때문입니다.jQuery로 여러 div 상자 만들기

실제로 여기에 질문이 있습니다 : 1. inner-div가있는 상자를 여러 개 만들 수 있도록 코드를 어떻게 변경합니까? 2. 마지막으로 만든 상자와 겹쳐 지도록 상자를 만들고 싶지만 10 px 오른쪽으로 이동 한 후 10 px 아래로 이동하려면 가장 좋은 방법은 무엇입니까?

감사합니다.

코드 :

PROGRAM.popup = function(width, height){ 
    this.width = width; 
    this.height = height; 
} 

PROGRAM.popup.prototype.buildPopup = function(){ 

$('<div/>', { 
    id: 'window', 
    width: this.width, 
    height: this.height, 
}).appendTo('#container'); 

$('<div/>', { 
    id: 'windowTop', 
    width: this.width, 
}).appendTo('#window'); 
} 

...

var popup = new PROGRAM.popup(300, 300); 
popup.buildWindow(); 

var popup2 = new PROGRAM.popup(300, 300); 
popup2.buildWindow(); 

답변

1
  1. window ID를 제거하고 스타일링을위한 클래스로 사용할 수 있습니다. 창 div에 대한 참조를 직접 변수에 저장하고 appendTo()에서 사용할 수 있습니다.

  2. 이전 창 div를 검색하고 offset()을 사용하여 위치를 얻으십시오. 그런 다음 해당 값을 기준으로 자체 오프셋을 설정하십시오.

자바 스크립트 :

PROGRAM.popup = function(width, height){ 
    this.width = width; 
    this.height = height; 
}; 

PROGRAM.popup.prototype.buildPopup = function(){ 

    // save reference to the created div 
    // this way we don't have to look for it in DOM 
    var win = $('<div/>', { 
    'class': 'window', 
    'width': this.width, 
    'height': this.height 
    }).appendTo('#container'); 

    // try to retrieve previous closest sibling with class "window" 
    var prev = win.prev('.window'); 
    // if it exists then get his position and set our based on it 
    if (prev.length) { 
    win.offset({ 
     left: prev.offset().left + 10, 
     top: prev.offset().top + 10 }); 
    } 

    // nothing changed here 
    $('<div/>', { 
    'class': 'inner', 
    'width': this.width 
    }).appendTo(win); 

}; 

HERE 코드입니다.

0

(2) 나는이 방법을 수행합니다

.mybox{ 
    padding-top: 10px; 
    padding-left: 10px; 
} 
<script> 
    var myHtml = '<div class="mybox"><a class="iconAction">icon</a></div>"; 
    $('body').append(myHtml); 
    $('body').on('click', 'a.iconAction',function(event){ 
     $(this).parent().append(myHtml) 
    }) 
</script> 
0

(1) 당신은 아마 ID를 제거해야합니다을 속성. 당신이 어떤 방법으로 ID를 참조해야하는 경우,이 같은 작업을 수행하여 대신 하드 코딩 된 값을 사용하여 처음부터 생성 :

function generateId(){ 
    var count = 0; 
    while(document.getElementById(id = 'anonymous_element_' + (count++))){} 
    return id; 
} 

(2) 물론, 가장 쉬운 솔루션이 된 div 절대적으로 배치하는 것 (position:absolute) 다른 div의 위치가 겹치지 않는 위치를 추적하십시오. 그것은 내가하고 싶은 것보다 더 많은 일처럼 들린다.