3

我正在使用同位素插件。我有一个空容器,我要在其中添加项目$(document).ready(...

所有这些项目都已正确添加,同位素的布局和链接过滤工作正常。

但是,我希望能够在将某个项目类附加到容器之后直接对它们应用过滤器,或者在插入期间甚至更好。

怎么做?

要恢复,我有一个“.home”过滤器,我想在所有项目都附加到容器后应用它,而不是需要单击“home”过滤器。

4

3 回答 3

12

如果你有一些简单的东西

<ul id="filters">
    <li><a href="#" data-filter=".home">Show all</a></li>
    <li><a href="#" data-filter=".what">What?</a></li>
    <li><a href="#" data-filter=".when">When?</a></li>
    <li><a href="#" data-filter=".why">Why?</a></li>
    // and so forth...
</ul>

一旦完全构建了 DOM,您就可以运行一个函数来预设过滤

$(function() {
    // Isotope stuff...
    $container.isotope({filter: '.home'});
    // more Isotope stuff...
});

和同位素已被初始化。请参阅此修改后的 DeSandro fiddle,其中过滤了初始视图以仅显示红色元素。

更新将初始内容加载到一个空的#container(通过Ajax?),您可以使用插入方法或只是隐藏#container,直到所有元素都已加载和排序。关于 Ajax 和成功初始化 Isotope,另请参见此处的 SO 答案

于 2012-08-17T16:37:46.300 回答
3

您可以使用同位素初始选项。

请检查这个基于“组合过滤器”官方示例的代码笔

// init Isotope
var $grid = $('.grid').isotope({
  itemSelector: '.color-shape',
  filter: '.initial-filter-class' //use this class with the items you want to load initially.
});

例如:

  <div class="color-shape small round red initial-filter-class"></div>
于 2018-12-26T07:38:14.207 回答
1

我参加聚会有点晚了,但我昨天和 Isotope 一起工作时遇到了同样的问题,最终以不同的方式解决了它。

假设我有一组过滤器按钮,很像 Systembolaget 的:

<div id="filters">
  <button data-filter="*">Show all</button>
  <button data-filter=".hidden">Archived</button>
  <button data-filter="*:not(.hidden)">Current</button>
</div>

也许我只想在用户完成加载页面时显示“当前”过滤器。我为与我想要的过滤器匹配的 CSS 选择器设置了一个变量。稍后我们将使用此变量。

var $grid;
var filterValue = "*:not(.hidden)";

接下来,我需要初始化我的内容。我已经准备好我的内容,所以我跳过了这一步,但如果你打算异步加载内容,你可以使用 JavaScript Promise。

这是我从Google 的 Promise 介绍文章中获取的示例:

var promise = new Promise(function(resolve, reject) {
  var content = [];

  // do a thing, possibly async, then…

  if (content.length > 0) {
    resolve(content);
  }
  else {
    reject(Error("Nothing loaded"));
  }
});

这是我用来设置同位素网格和事件监听器的函数:

function init() {
  // Initialize isotope and the filter method we want to use
  $grid = $('.grid').isotope({
    itemSelector: '.grid-item',
    filter: function() {
      return filterValue ? $(this).is(filterValue) : true;
    }
  });

  // Event listener for the filter buttons
  $('#filters').on('click', 'button', function() {
    filterValue = $(this).attr('data-filter');

    $(this).addClass('active')
           .siblings().removeClass('active');

    // Refresh the isotope grid to display the filtered items
    $grid.isotope();
  });
} 

一旦你定义了 Promise 应该做什么,你就可以初始化你的同位素网格。您需要将它嵌套在then方法中,以便它仅在 promise 成功解决后运行。这还允许您设置在内容加载步骤失败的情况下应该运行的任何后备。

promise.then(function(results) {

  // Function defined in the last code snippet
  return init();

}, function(err) {
  // Error: "Nothing loaded"
  console.log(err); 

  // If you have a banner hidden on the page, you can display it
  $('.message').show();
});

如果您不需要使用承诺(例如我的情况),那么您需要做的就是:

init();
于 2019-06-11T16:59:20.430 回答