2011-12-16 207 views
0

我希望能夠通過單擊圖標創建類似框的窗口。如果我創建了一個,然後再次單擊,則會創建另一個,依此類推。通過我的代碼,我可以創建幾個框,但是內部div只能在第一個打開的窗口中創建。其原因是,如果創建了幾個盒子,div將擁有id,這當然不是正確的做法。使用jQuery創建多個div盒子

我其實在這裏有問題: 1.我怎樣才能改變我的代碼,所以我可以用inner-div創建幾個盒子? 2.如果我想要做的最好的方法是什麼我想要一個創建的框與最後創建的框重疊,但將右側10像素向下移動10像素?

謝謝!

代碼:

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並將其用作樣式的類。您可以將參考值直接保存到變量中並在appendTo()中使用。

  2. 檢索上一個窗口div並使用offset()獲取他的位置。然後根據這些值設置自己的偏移量。

的JavaScript:

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的定位位置,以使它們不重疊。這聽起來像比我想要做的更多的工作。