如何在Isotope筛选功能中限制展示的条目数量
Isotope 筛选结果限制展示6条解决方案
你可以通过自定义Isotope的filter过滤函数,对符合筛选条件的元素做计数限制,仅前6个匹配项返回显示状态即可实现需求,修改后的完整代码如下:
//isotope : filtering jQuery(function($) { // init Isotope var $grid = $('.grid_posts').isotope({ // options itemSelector: '.grid_posts-item', layoutMode: 'fitRows', }); // filter items on button click $('.filter-button-group').on('click', '.filter-ecm', function () { var filterValue = $(this).attr('data-filter'); let matchCount = 0; // 每次筛选前重置匹配计数 $grid.isotope({ filter: function() { // 先判断当前元素是否符合筛选条件 const isMatch = filterValue === '*' ? true : $(this).is(filterValue); if (isMatch) { matchCount++; // 仅前6个匹配项返回true(显示),超出的返回false(隐藏) return matchCount <= 6; } return false; } }); }); //change class on items selected $('.button-group').each( function( i, buttonGroup ) { var $buttonGroup = $( buttonGroup ); $buttonGroup.on( 'click', '.filter-ecm', function() { $buttonGroup.find('.is-checked').removeClass('is-checked'); $( this ).addClass('is-checked'); }); }); });
核心修改说明
- 替换了原来直接传入
filterValue的逻辑,改为自定义过滤函数 - 每次触发筛选时初始化匹配计数变量
matchCount,每匹配到一个符合条件的元素就计数+1 - 仅当匹配数≤6时返回显示状态,超出的匹配项也会被隐藏
- 兼容原有的全选(
data-filter="*")场景,不会影响原有筛选逻辑的兼容性
内容的提问来源于stack exchange,提问作者chtouk
相关产品推荐
相关产品推荐

