【发布时间】:2014-06-07 15:15:10
【问题描述】:
这是我创建的一个脚本,目的是在流体/固定容器中很好地显示画廊。
关键是将缩略图均匀地放置在它们的行中,同时保持每行的第一个和最后一个缩略图相对于其容器。
为此,我需要计算要应用于每个缩略图的边距,这就是该脚本的内容(只有最后一部分是相关的,但我将其全部放在这里以防万一)。
我检查了变量,它们都正常,但无论出于何种原因,脚本末尾的“nth-child”选择器内的变量不是选择性的,即使变量正确,也会应用样式到“pic_block”类的所有实例:
<script>
$(document).ready(function() {
// Get the width of the container and thumbnails
var containerWidth = $('.container').width();
var boxWidth = $('.pic_block').width();
// How many thumbnails can I have per row?
var boxesPerRow = Math.floor(containerWidth/boxWidth);
// And then what is the remaining space left between the last thumbnail and the container?
var marginTotalWidth = (containerWidth-(boxesPerRow*boxWidth));
// What is the maximum margin-right I can set to get an equal distance between the thumbnails (except the last box)?
var tempMarginR = Math.floor(marginTotalWidth/(boxesPerRow-1));
// Then, what is the space still remaining between the last thumbnail and the container?
var extraTotalSpaceWidth = ((marginTotalWidth/(boxesPerRow-1)) - tempMarginR) *boxesPerRow;
// Time to set some variables that would help me dispatching the remainig space between the thumbnails
var p = 1;
var i = extraTotalSpaceWidth;
var marginR = [];
// By default, all the thumbnails in a row (but the last one) get the same margin-right -> this will be fined-tuned in a later loop
while(p <= boxesPerRow)
{
if(p < boxesPerRow)
{
marginR[p]=tempMarginR;
}
else
{
marginR[p]=0;
}
$('.pic_block:nth-child('+ p +'n)').css('margin-right',marginR[p]);
p++;
}
// And if, after that, there is still at least 1px of extra space left...
while(i >= 1)
{
var s=1;
// add incrementaly an extra margin to the right of each thumbnail of a row (except the last one) until there is no more space left
while( s < boxesPerRow)
{
marginR[s] = marginR[s]++;
if(i >= 1)
{
/********************************************************************/
/* Here is the problem: this doesn't only apply to the nth-children */
/* determined by the "s" variable, it applies to all the class. */
/********************************************************************/
$('.pic_block:nth-child('+ s +'n)').css('margin-right', marginR[s]);
i--;
};
s++;
}
};
});
</script>
完整代码(包括 html/css)在这里是:http://jsfiddle.net/Pf7VV/
任何帮助将不胜感激。
谢谢。
【问题讨论】:
-
如果变量恰好是 '3',你有 ('+s+'n)') 将是 :nth-child('3n)')
-
我相信您是说我有“额外报价”问题,但我没有看到。 $('.pic_block:nth-child('+ s +'n)') 不会变成 $('.pic_block:nth-child(3n)') 吗?如果没有,你能更具体一点吗?谢谢!
-
对不起,我上次评论的困惑。我玩了一点你的代码,想知道图像的数量是否会根据屏幕的大小而变化,或者它们是否只是改变大小?现在在你的代码中 $('.pic_block:nth-child('+s+'n)') 是正确的,但是 s=1 ,所以你使用的 nth-child 是 1n。也就是说,每个孩子都被选中。如果您更改该数字,那么它将选择该数量的孩子,因此 s=2 将选择每隔一个孩子 s=3 将是每隔三个孩子。
-
图像的数量和大小都不会改变。当每行的第一个和最后一个缩略图靠在容器上时,我想将它们均匀地对齐。剩下的就是这个想法:对所有子元素应用默认边距(1n),然后对最后一个缩略图应用“无边距”样式(:nth-child(boxesPerRow)),最后添加额外边距到一些特定的缩略图,以便清空每行的最后一个缩略图和容器之间的任何间隙。这个额外的边距可以应用于每行的第一个元素 (n)、第二个 (2n)、第三个 (3n) 等。
-
jsfiddle.net/Pf7VV/2 看起来中心 div 的边距与第一个和第二个的间距不同,这就是您要找的吗?
标签: jquery variables jquery-selectors