过滤块 v2

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您的旅程每个阶段提供云产品。 立即开始使用 $200 免费积分!

这是对 第一个版本 过滤块的更新,我之前做了一段时间。 想法是您在页面上有一个长列表或大型“块”集。 每个块属于某个组。 页面上有导航用于一次查看所有块,或选择要查看的组。 选择特定组将隐藏来自任何其他组的块,因此称为“过滤”。

 

查看演示   下载文件

 

HTML

每个块都应用了类名,以表示它所属的组。 这里有两个例子。 它们都属于“all”组,上面的一个是“adv”,下面的一个是“cla”。

<div class="all adv">
<img src="images/flavor-curry.jpg" alt="" />
<h4>Sweet Curry With Saffron</h4>
<p>Lusciously mellow with notes of overripe berries, 55% Hawaiian dark chocolate meets its soulmate in sweet curry - awash in spices including coriander, tumeric, cumin and cardamom and sprinkled with rare saffron. This spicy melange is slowly steeped in fresh coconut puree and gently blended with the chocolate. The taste rushes over you in waves - fragrant curry, chased by coconut, then the lingering, raisiny sweetness of chocolate. Available in <a href="/store/products/Chocolatier_s_Choice-5-2.html">Chocolatier's Choice</a> and <a href="/store/products/Adventurous_Collection-3-2.html">Adventurous Collection</a>.</p>
</div>

<div class="all cla">
<img src="images/flavor-vanilla.jpg" alt="" />
<h4>Lucille's Vanilla </h4>
<p>For those who prefer milder chocolate, this winsome truffle will ignite a lifelong love affair. Gail uses a dark blend in this recipe handed down through four generations of the Guittard family of chocolate makers. It tastes like a rich spoonful of homemade chocolate pudding - just like Gail's mom, Lucille, made on the stovetop in their family farm's kitchen. Available in <a href="/store/products/Chocolatier_s_Choice-5-2.html">Chocolatier's Choice</a> and <a href="http://gailambrosius.com/store/products/Classic_Collection-2-2.html">Classic Collection</a>.</p>
</div>

然后,导航包括引用这些类的 REL 属性。

<div id="flavor-nav">
    <a rel="all" class="current">All</a> 
    <a rel="cla">Classic</a> 
    <a rel="adv">Adventurous</a> 
    <a rel="tea">Tea-Inspired</a> 
</div>

jQuery JavaScript

用简单的英语来说,计划是

  1. 当单击过滤导航中的链接时…
  2. 淡出所有块(视觉指示正在发生变化)
  3. 从所有导航中删除“current”类并将其应用到新单击的导航
  4. 根据 REL 属性确定应显示哪个组
  5. 任何不属于该组的类型,向上滑动
  6. 任何属于该组的类型,向下滑动
  7. 淡入所有块
$(function() {

	var newSelection = "";
	
	$("#flavor-nav a").click(function(){
	
	    $("#all-flavors").fadeTo(200, 0.10);
	
		$("#flavor-nav a").removeClass("current");
		$(this).addClass("current");
		
		newSelection = $(this).attr("rel");
		
		$(".flavor").not("."+newSelection).slideUp();
		$("."+newSelection).slideDown();
		
	    $("#all-flavors").fadeTo(600, 1);
		
	});
	
});

这比我们在版本 1 中体验到的更流畅。 主要是因为使用了 .not() 原生 jQuery 过滤器。 以前,我们只是“向上滑动”所有类型,然后“向下滑动”正确的类型。 这意味着每次导航更改时,每个类型都会经历动画。 但是这并不总是必要的。 例如,如果您正在查看一个子集,然后单击返回“all”,则当前显示的块无需进行动画处理,只需所有其他块扩展出来即可。 这解决了这个问题。