我正在从数据库中提取图像/元素列表并根据类别过滤它们。
设计要求是平铺/马赛克布局,在第 7 项上有一个大正方形,在第 8 项上有一个较大的矩形,在所有过滤器上。这意味着较大的方 block 不能以不同的顺序排列。
目前我的方法是使用第 n 个子选择器从元素列表中选择第 7 个和第 8 个:
/* create big item block */
.grid-item:nth-child(7n) {
height: 24em;
width: 50%;
}
/* create rectangle item block */
.grid-item:nth-child(8n) { width: 50%; }
这是一个问题,因为它只影响整个列表。选择按钮/类别后,如何定位筛选列表中的第 7 项和第 8 项?
这是我试图为全 View 过滤器实现的具有正确布局的代码笔。我正在尝试实现相同的布局,但使用基于过滤器的不同元素。如果您选择“thank-you”类别,您可以看到大方 block 被拉到列表中的第 3 位,并且由于第 n 个子选择器仍然是一个大方 block 。
最佳答案
问题是双重的:
- isotope 不会删除过滤掉的元素,而是使用
display:none
隐藏它们。因此元素仍然可以通过 CSS 中的nth-child()
选择器进行选择。 - 需要在重新排列网格之前调整元素的大小,因此在调用
grid.isotope({filter: ...})
之前。
因此,CSS 无法自行完成这项工作。需要更多的 javascript。
一种方法是:
- 设置“arrangeComplete”事件处理程序以调整网格元素的大小并调用
grid.isotope()
重新排列它们, - 调用
grid.isotope({ filter: ... })
并允许事件处理程序在应用过滤器后触发。
这会起作用,但用户会看到双重重排。
// bind filter button click
$('#filters').on('click', 'button', function() {
var filterValue = $(this).attr('data-filter');
grid.one('arrangeComplete', function(event, laidOutItems) {
// Triggered after a layout and all positioning transitions have completed.
$('.grid .grid-item').filter(':visible').removeClass('big rectangle')
.eq(6).addClass('big') // the 7th item
.end()
.eq(7).addClass('rectangle'); // the 8th item
grid.isotope(); // re-trigger isotope
});
grid.isotope({ filter: filterFns[filterValue] || filterValue });
}).find('button').eq(0).trigger('click');// trigger click on default button to initialize everything.
为了更好的视觉效果,你可以变聪明:
- 通过过滤包含网格中所有元素的 jQuery 集合,手动“预应用”过滤器,不应用同位素过滤器,
- 仍然在 jQuery 集合中,选择第 7/8 个元素(从那些将可见的元素中)并调整它们的大小,
- 最后,再次使用相同的过滤器,调用
grid.isotope({filter: ...})
实际重新排列网格。
这样,网格只需要重新排列一次,视觉效果会更赏心悦目。
幸运的是,jQuery 链接使代码相当简单:
// bind filter button click
$('#filters').on('click', 'button', function() {
var filterValue = $(this).attr('data-filter');
grid.find('.grid-item')
.removeClass('big rectangle')
.filter(filterFns[filterValue] || filterValue)
.eq(6).addClass('big') // the 7th item
.end()
.eq(7).addClass('rectangle') // the 8th item
grid.isotope({ filter: filterFns[filterValue] || filterValue });
}).find('button').eq(0).trigger('click');// trigger click on default button to initialize everything.
在这两种方法中,将样式表中的两个“.grid-item:nth-child”指令替换为:
.grid-item.big {
height: 24em;
width: 50%;
}
.grid-item.rectangle { width: 50%; }
注意:要仅设置第 7/8 个元素的样式,而不是第 15/16、23/24 等项,不要使用 nth-child。
关于javascript - 如何在过滤列表中使用第 nth-child?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39379177/