如何在筛选列表上使用 nth-child?

How to use nth-child on a filtered list?

我正在从数据库中提取 images/items 的列表并根据类别过滤它们。

设计要求是 tiled/mosaic 布局,在第 7 项上有一个大正方形,在第 8 项上有一个较大的矩形,在所有过滤器上。这意味着较大的方块不能以不同的顺序排列。

目前我的方法是使用 nth-child select 或者 select 项目列表中的第 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%; }

这是一个问题,因为它只影响整个列表。在 button/category 被 select 编辑后,如何定位筛选列表中的第 7 和第 8 项?

这是我试图为 view-all 过滤器实现的具有正确布局的代码笔。我正在尝试实现相同的布局,但使用基于过滤器的不同项目。如果你是 select 'thank-you' 类别,你可以看到大方块被拉到了这个列表的第三位,并且由于 nth-child selector 仍然是一个大方块。

http://codepen.io/H0BB5/pen/BLNLWy

问题是双重的:

  • isotope 不会删除过滤掉的项目,而是用 display:none 隐藏它们。因此 selectselectCSSselect 或 CSS.
  • 中的 select
  • 需要在重新排列网格之前执行项目大小调整,因此在调用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.

为了更好的视觉效果,你可以变聪明:

  • "pre-apply"手动过滤器,不应用同位素过滤器,通过过滤包含网格中所有项目的jQuery集合,
  • 仍在 jQuery 集合中,select 第 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.

demo

在这两种方法中,将样式 sheet 中的两个“.grid-item:nth-child”指令替换为:

.grid-item.big { 
  height: 24em;
  width: 50%; 
}
.grid-item.rectangle { width: 50%; }

注意:要仅设置第 7/8 个项目的样式,而不是第 15/16、23/24 等项,不要使用第 nth-child