對Alex給出的腳本做了一些小的改進,以完全滿足我的需求。現在每行的第一個縮略圖沒有左邊距,每行的最後一個縮略圖沒有右邊距,所以縮略圖確實使我們看到了容器div的全部寬度。還使用jQuery的.outerWidth()而不是.width()來檢索縮略圖的寬度,以便在不影響計算的情況下使用邊框等。現在,腳本也會在DOM加載後立即運行,從頭開始計算適當的邊距,而不僅僅是在窗口重新調整大小時。
這裏是新的腳本:
<script type="text/javascript">
$(document).ready(calculateThumbnailMargin);
$(window).resize(calculateThumbnailMargin);
function calculateThumbnailMargin() {
// Define a minimum margin
var minimumMargin = 20;
// Get the outer width of the thumbnail (including padding and border)
var thumbWidth = $('.video-thumbnail-container').outerWidth();
// Calculate how man thumbnails can fit on one row
var numberofdivs = $('#content-area').width()/thumbWidth;
numberofdivs = Math.floor(numberofdivs).toFixed(0);
if (numberofdivs >= $('.video-thumbnail-container').size()) {
numberofdivs = $('.video-thumbnail-container').size();
};
// Calculate the remaining width of the row
var widthleft = $('#content-area').width() - (thumbWidth * numberofdivs);
// Calculate the proper margin to use
var margin = (widthleft/(numberofdivs - 1))/2;
// Check that the margin is not less than the minimum margin
if (margin < minimumMargin) {
// Use one less thumnail on each row
numberofdivs = numberofdivs - 1;
// Calculate the remaining width of the row
widthleft = $('#content-area').width() - (thumbWidth * (numberofdivs));
// Calculate the proper margin to use
margin = (widthleft/(numberofdivs - 1))/2;
}
// Add the proper margin to each thumbnail
$('.video-thumbnail-container').attr('style', 'margin-left:' + margin + 'px; margin-right:' + margin + 'px');
// Remove the left-margin on the first thumbnail on each row and the right-margin on the last thumbnail on each row
for (i = 0; i < $('.video-thumbnail-container').size(); i = i+numberofdivs) {
$(".video-thumbnail-container:eq(" + i + ")").css('marginLeft', 0);
$(".video-thumbnail-container:eq(" + (i + numberofdivs - 1) + ")").css('marginRight', 0);
}
}
http://stackoverflow.com/questions/6359180/jquery-setting-a-dynamic-margin – Chad 2011-06-15 14:28:16
議員,不要使用表格。 – Alex 2011-06-15 14:34:45
感謝您的鏈接,這將解決我的問題!但是,當你必須爲每個邊距添加空td:s時,感覺就像是一個有點難看的解決方案。 – 2011-06-15 14:37:01