2013-10-15 88 views
0

我使用黑客justify divs in the container(標記爲答案)。它在靜態HTML中完美工作。通過JavaScript添加元素後,CSS黑客不工作

<div id="gallery-thumbnails"> 
    <div class="gallery-thumbnail"> 
     <img src="1.jpg" alt="alt" title="title"> 
    </div> 
    <div class="gallery-thumbnail"> 
     <img src="2.jpg" alt="alt" title="title"> 
    </div> 
    <div class="gallery-thumbnail"> 
     <img src="3.jpg" alt="alt" title="title"> 
    </div> 
    <div class="gallery-thumbnail"> 
     <img src="4.jpg" alt="alt" title="title"> 
    </div> 
    <span class="stretch"></span> 
</div> 

但我通過JS做到這一點的時候,黑客本身不工作(顏色樣式應用於,我見圖片)。 Hovewer,diff工具表示靜態和生成的DOM版本是相同的。

下面的代碼

var thumbnailsContainer = $('#gallery-thumbnails'); 
$(thumbnailsContainer).children('*').each(function() { 
    $(this).remove(); 
}); 

$(lists[index]).children('img').each(function(index, picture) { 
    var thumbnail = $('<div>', { class: "gallery-thumbnail" }); 
    var thumbnailImage = $('<img>', { src: $(picture).attr('src'), alt: $(picture).attr('alt'), title: $(picture).attr('title') }); 
    $(thumbnail).append(thumbnailImage); 
    $(thumbnailsContainer).append(thumbnail); 
}); 

$(thumbnailsContainer).append($('<span>', { class: 'stretch'})); 

更新

JSFiddle is here。如果您評論JS代碼並重新運行,您將看到我的意圖。如果你取消註釋,你會看到我失敗。

+1

什麼不工作?你從來沒有真正說過。 – cgatian

+0

@cgatian黑客。當我通過JS製作DOM時,Div並不合理。 – efpies

+0

請提供一個jsfiddle。 – Oriol

回答

1

的問題是,你需要元件之間的空間,所以只需添加

$thumbnailsContainer.append(' '); 

Demo

+0

不可信!你是我的救星。但你能解釋一下嗎?它對我來說看起來像是一種魔力。 – efpies

+0

你需要空間,因爲如果你的元素之間有任何東西,任何東西都可以將它們分開,並且你希望它們分開。 – Oriol

相關問題