我正在做一个网店,商品像往常一样在网格中显示为“图 block ”。我只想使用各种尺寸的图 block 并确保(通过 jQuery)没有可用空间。
在基本情况下,我有一个 960 像素的包装器,想使用 240x180 像素(类 .grid_4)图 block 和 480x360 像素(类 .grid_8)图 block 。查看图像(想象那里没有边距/填充):
alt text http://img580.imageshack.us/img580/2828/screenshot2010041508h52.png
没有 jQuery 的问题:
- 当 CMS 提供第 6 个大图 block 时,第 5 个图 block 下面会有一个空闲空间
- 当 CMS 提供大块为第 7 block 时,第 5 block 和第 6 block 下方会有空闲空间
- 当 CMS 提供第 8 个大图 block 时,它会移动到下一行,留下第 8 个位置空闲
目前我的解决方案是这样的:
$(".grid_8").each(function(){
//console.log("BIG on position "+($(this).index()+1)+" which is "+(($(this).index()+1)%2?"ODD":"EVEN"));
switch (($(this).index()+1)%4) {
case 1:
// nothing needed
//console.log("case 1");
break;
case 2:
//need to shift one position and wrap into 240px div
//console.log("case 2");
$(this).insertAfter($(this).next()); //swaps this with next
$(this).prevAll(":nth(0), :nth(1)").wrapAll("<div class=\"grid_4\" />");
break;
case 3:
//need to shift two positions and wrap into 480px div
//console.log("case 3");
$(this).prevAll(":nth(0), :nth(1)").wrapAll("<div class=\"grid_4\" />"); //wraps previous two - forcing them into column
$(this).nextAll(":nth(0), :nth(1)").wrapAll("<div class=\"grid_4\" />"); //wraps next two - forcing them into column
$(this).insertAfter($(this).next()); //moves behind the second column
break;
case 0:
//need to shift one position
//console.log("case 4");
$(this).insertAfter($(this).next());
//console.log("shifted to next line");
break;
}
});
从评论中应该可以清楚地看出它是如何工作的——通常总是通过在需要时向后移动一个位置来确保大瓷砖位于奇数位置(前面的小瓷砖的数量是偶数)。大图 block 左侧的小图 block 也需要包裹在另一个 div 中,以便它们显示在列中而不是行中。
现在终于有问题了:
- 如何概括该函数以便我可以使用更多的图 block 尺寸,例如 720x360 (3x2)、480x540 (2x3) 等?
- 有没有办法简化这个功能?
- 我需要确保在检查实际位置时大方 block 算作小方 block 的倍数。因为在位置 12 的图 block (第 3 行的最后一个图 block )上使用 index() 现在会返回 7(位置 8),因为位置 5 和 9 的图 block 被包裹在一列中,而大图 block 也只是一个 div,但跨越 2x2 个位置。有什么干净的方法可以确保这一点?
非常感谢您的任何提示。随意重用代码,我认为它很有用。
约瑟夫
最佳答案
听起来您需要使用名为 masonry 的 jQuery 插件。
你可以找到它here
关于javascript - 你能简化和概括这个有用的 jQuery 函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2643358/