这是一款使用 html5 和 jQuery 制作的非常实用的图片分类过滤特效插件。
HTML结构
html结构使用的是一个无序列表来制作图片画廊,给它一个id #stage。雷一个列表元素都带有一个 HTML5 data 属性,该属性的值可以使用逗号来分割一系列的值。在后面我们会用jQuery来循环这些列表项,然后记录这些值,并用它们来做为图片分类的依据。
<ul id="stage">
<li data-tags="Print Design">
<img src="assets/img/shots/1.jpg" />
</li>
<li data-tags="Logo Design,Print Design">
<img src="assets/img/shots/2.jpg" />
</li>
<li data-tags="Web Design,Logo Design">
<img src="assets/img/shots/3.jpg" />
</li>
...
</ul>
jQuery代码
这款插件中还集成了另一个jQuery插件-Quicksand 。它用于比较两个列表的列表项,然后在它们当中找到匹配的列表项,并将它们移动到新的位置上。我们首先要循环id为#stage的无序列表,并创建一个隐藏的无序列表来存放找到的匹配列表项。同时也会创建一个菜单项用于触发两个列表之间的quicksand动画。
$(document).ready(function(){
var items = $('#stage li'),
itemsByTags = {};
// Looping though all the li items:
items.each(function(i){
var elem = $(this),
tags = elem.data('tags').split(',');
// Adding a data-id attribute. Required by the Quicksand plugin:
elem.attr('data-id',i);
$.each(tags,function(key,value){
// Removing extra whitespace:
value = $.trim(value);
if(!(value in itemsByTags)){
// Create an empty array to hold this item:
itemsByTags[value] = [];
}
// Each item is added to one array per tag:
itemsByTags[value].push(elem);
});
});
每一个找到的项都被放入到itemsByTags对象数组中。这意味着itemsByTags['Web Design']将会保存所有data属性中带有Web Design的列表项。我们将使用这个对象来为quicksand创建隐藏的无序列表。
最好是创建一个辅助函数来帮助我们创建隐藏列表:
function createList(text,items){
// This is a helper function that takes the
// text of a menu button and array of li items
// Creating an empty unordered list:
var ul = $('<ul>',{'class':'hidden'});
$.each(items,function(){
// Creating a copy of each li item
// and adding it to the list:
$(this).clone().appendTo(ul);
});
ul.appendTo('#container');
// Creating a menu item. The unordered list is added
// as a data parameter (available via .data('list')):
var a = $('<a>',{
html: text,
href:'#',
data: {list:ul}
}).appendTo('#filter');
}
这个辅助函数使用组的名称和列表项数组作为参数。然后它将这些列表项复制到一个新的列表中,并将它链接到菜单项上面。
有了这个辅助函数,现在我们可以循环所有的组,然后使用该函数完成相应的动作,并监听菜单的click事件。
// Creating the "Everything" option in the menu:
createList('Everything',items);
// Looping though the arrays in itemsByTags:
$.each(itemsByTags,function(k,v){
createList(k,v);
});
$('#filter a').live('click',function(e){
var link = $(this);
link.addClass('active').siblings().removeClass('active');
// Using the Quicksand plugin to animate the li items.
// It uses data('list') defined by our createList function:
$('#stage').quicksand(link.data('list').find('li'));
e.preventDefault();
});
// Selecting the first menu item by default:
$('#filter a:first').click();