0

我一直在从事一个新项目,可以在此处查看其演示。大多数事情都准备好了,但我的主要问题来自我正在使用的 jQuery 投资组合插件。您可以在此处查看其用法演示。您可以在标题默认设置下的演示页面上看到,每页有12 个项目,它使用自定义标题在 XML 生成页面上定义的类别之间进行过滤,代码如下;

<?xml version="1.0" encoding="UTF-8"?>
<portfolio>

<categories>
    <category id="cardgames">Card Games</category>
    <category id="environments">Environments</category>
    <category id="character">Character</category>
    <category id="animations">Animations</category>
</categories>
<!-- Items Start -->
<items>
<!-- Individual Item Starts -->
    <item>
        <thumbnail>images/thumbnails/1-thumb.jpg</thumbnail>
        <preview>images/jpegs/1.jpg</preview>
        <category>cardgames,environments,character,animations</category>
        <description>Description goes here</description>
    </item>
<!-- Individual Item Ends -->
<!-- Individual Item Starts -->
    <item>
        <thumbnail>images/thumbnails/2-thumb.jpg</thumbnail>
        <preview>images/jpegs/2.jpg</preview>
        <category>cardgames,environments,character,animations</category>
        <description>Description goes here</description>
    </item>
<!-- Individual Item Ends -->
<!-- Individual Item Starts -->
    <item>
        <thumbnail>images/thumbnails/3-thumb.jpg</thumbnail>
        <preview>images/jpegs/3.jpg</preview>
        <category>cardgames,environments,character,animations</category>
        <description>Description goes here</description>
    </item>
<!-- Individual Item Ends -->
<!-- Individual Item Starts -->
    <item>
        <thumbnail>images/thumbnails/4-thumb.jpg</thumbnail>
        <preview>images/jpegs/4.jpg</preview>
        <category>cardgames,environments,character,animations</category>
        <description>Description goes here</description>
    </item>
<!-- Individual Item Ends -->
<!-- Individual Item Starts -->
    <item>
        <thumbnail>images/thumbnails/5-thumb.jpg</thumbnail>
        <preview>images/jpegs/5.jpg</preview>
        <category>cardgames,environments,character,animations</category>
        <description>Description goes here</description>
    </item>
<!-- Individual Item Ends -->
</items>
</portfolio>

您可以看到过滤器的类别是在 XML 上定义的,然后通过第二个 JavaScript 调用,代码是;

(function($){
$.fn.portfolioSetter=function(options){
    var defaults={
        //default settings
        itemsPerPage: 10, //the number of items per page
        pageWidth: 840,  //the width of each page
        pageHeight:320,  //the height of each page
        itemMargin:15,  //margin of each of the portfolio items
        showCategories: false,  // if set to false, the categories will be hidden
        allText: 'ALL', //the ALL text displayed before the categories names
        easing: 'easeOutExpo', //the animation easing
        animationSpeed: 800, //the speed of the animation of the pagination
        navButtonWidth:30,  //the width of the pagination button 
        wavyAnimation:false, //if set the true, all the elements will fade in consecutively with a wavy effect
        xmlSource : 'portfolio.xml',  //the XML file from which the data is exctracted
        pageWrapperClass: 'page_wrapper',  //the class of the div that wraps the items in order to set a page
        navigationId: 'portfolio_pagination',  //the ID of the pagination div
        categoriesId: 'portfolio_categories', //the ID of the categories div
        itemClass: 'portfolio_item' //the class of the div that wraps each portfolio item data
    };

    var options=$.extend(defaults, options);
    options.pageHolder=$(this);

    //define some helper variables
    var categories=[], items=[], pageWrappers=[], imagesLoaded=0, counter=0, ie=false, categoryHolder;

    var root=$('<div />').css({width:(options.pageWidth*2), height:options.pageHeight, float:'left'});
    $(this).css({width:options.pageWidth, height:'auto', overflow:'hidden'}).append(root);
    var parentId=$(this).attr('id');


init();
function init() {
    root.parent().append('<div class="loading"></div>');
    loadItems();
}

/**
 * Parses the XML portfolio item data.
 */
function loadItems(){
    $.ajax({
        type:'GET',
        url: options.xmlSource,
        dataType:'xml',
        success:function(xml){

            //get the settings
            if($(xml).find('show_categories:first').text()==='off'){
                options.showCategories=false;
            }               

            if(options.showCategories){
                //get the portfolio categories
                $(xml).find('categories').eq(0).find('category').each(function(i){
                    var current=$(this);
                    var category = {
                        id: current.attr('id'),
                        name: current.text()
                    };
                    categories.push(category);
                });
            }

            //get the portfolio items
            $(xml).find('item').each(function(i){
                var current=$(this);
                var thum=current.find('thumbnail:first').text();
                var prev = current.find('preview:first').text();
                var cat=current.find('category:first').text().split(',');
                var desc = current.find('description:first').text();

                var item = {
                    thumbnail:thum,
                    preview:prev,
                    category:cat,
                    description:desc,
                    obj:$('<div class="'+options.itemClass+'"><a rel="lightbox_'+parentId+'" class="single_image" href="'+prev+'" title="'+desc+'"><img src="'+thum+'" /></a></div>')
                };
                items.push(item);
            });

            setSetter();
        }
    });
}

/**
 * Calls the main functions for setting the portfolio items.
 */
function setSetter(){

    if($.browser.msie){
        ie=true;
    }
    root.siblings('.loading').remove();
    root.after('<div id="'+options.navigationId+'"><ul></ul></div>');
    if(options.showCategories){
        displayCategories();
    }
    loadImages();

}

/**
 * Displays the categories.
 */
function displayCategories(){

    categoryHolder=$('<div id="'+options.categoriesId+'"></div>');  
    categoryHolder.append('<div id="portfolio_categories_left"></div><ul></ul><div id="portfolio_categories_right"></div>');
    root.before(categoryHolder);
    var catUl=categoryHolder.find('ul#links');


    //add the ALL link
    var allLink= $('<li>'+options.allText+'</li>');
    catUl.append(allLink);
    showSelectedCat(allLink);

    //bind the click event
    allLink.bind({
        'click': function(){
            displayItems();
            showSelectedCat($(this));
        },
        'mouseover':function(){
            $(this).css({cursor:'pointer'});
        }
    });

    //add all the category names to the list
    var catNumber=categories.length;
    for(var i =0; i<catNumber; i++)(function(i){
        var category = $('<li>'+categories[i].name+'</li>');
        catUl.append(category);

        //bind the click event
        category.bind({
            'click': function(){
                displayItems(categories[i].id);
                showSelectedCat($(this));
            },
            'mouseover':function(){
                $(this).css({cursor:'pointer'});
            }
        });
    })(i);
}

function showSelectedCat(selected){
    //hide the previous selected element
    var prevSelected=categoryHolder.find('ul li.selected');
    if(prevSelected[0]){
        var prevHtml=prevSelected.find('div.port_cat').html();
        prevSelected.html(prevHtml);
        prevSelected.removeClass('selected');
    }

    //show the new selected element
    var html = selected.html();
    selected.html('<div class="port_cat_active"><div class="port_cat_l"></div><div class="port_cat">'+html+'</div><div class="port_cat_r"></div> </div>');
    selected.addClass('selected');
}

/**
 * Loads the images. When all the images are loaded calls the displayItems 
 * function to display the images.
 */
function loadImages(){
    var imageCount=items.length;
    for(var i in items){
        if(items.hasOwnProperty(i)){
         var img = new Image();
            $(img).load(function() {
                imagesLoaded++;
                if(imagesLoaded===imageCount){
                    //all the images are loaded, display them all
                    displayItems();
                }
            }).attr('src', items[i].thumbnail);  
        }
    }
}

/**
 * Displays the portfolio items.
 */
function displayItems(){

    var filterCat=arguments.length===0?false:true;

    //reset the divs and arrays

    root.html('');
    root.width(200);
    pageWrappers=[];
    root.animate({marginLeft:0});

    var length=items.length;    

    counter=0;
    var catId=arguments[0];
    for ( var i = 0; i < length; i++)
        (function(i, filterCat, catId) {

            if(!filterCat || (filterCat && items[i].category.contains(catId))){
                if(counter%options.itemsPerPage===0){
                    //create a new page wrapper and make the holder wider
                    root.width(root.width()+options.pageWidth+20);
                    var wrapper=$('<div class="'+options.pageWrapperClass+'"></div>').css({float:'left', width:options.pageWidth+options.itemMargin, height:options.pageHeight});
                    pageWrappers.push(wrapper);
                    root.append(wrapper);
                }

                if(ie){
                    //var obj=$('<div class="'+options.itemClass+'" style="background-image:url('+items[i].thumbnail+');" ><a rel="lightbox" class="single_image" href="'+items[i].preview+'" title="'+items[i].description+'"></a><img class="hidden" /></div>');
                    var obj=$('<div class="'+options.itemClass+'" ><a rel="lightbox_'+parentId+'" class="single_image" href="'+items[i].preview+'" title="'+items[i].description+'"><img src="'+items[i].thumbnail+'" /></a></div>');
                    pageWrappers[pageWrappers.length-1].append(obj.css({display:'none'}));
                    items[i].obj=obj;
                }else{
                    pageWrappers[pageWrappers.length-1].append(items[i].obj.css({display:'none'}));
                }

                var timeout=counter>=options.itemsPerPage?0:100;

                if(counter>=options.itemsPerPage || !options.wavyAnimation){
                    items[i].obj.fadeIn().animate({opacity:1},0);
                }else{
                    setTimeout(function() {
                        //display the image by fading in
                        items[i].obj.fadeIn().animate({opacity:1},0);
                    },counter*100);
                }

                counter++;
            }
    })(i,filterCat, catId);

    //call the lightbox plugin
    $('a[rel="lightbox_'+parentId+'"]').colorbox({current:"{current}/{total}"});

    //show the navigation buttons
    showNavigation();
    setHoverFunctionality();

}


/**
 * Displays the navigation buttons.
 */
function showNavigation(){
    //reset the divs and arrays
    var navUl=root.siblings('#'+options.navigationId).find('ul');
    navUl.html('');

    var pageNumber=pageWrappers.length;
    if(pageNumber>1){
        for(var i=0; i<pageNumber; i++)(function(i){
            var li = $('<li></li>');
            navUl.append(li);
            //bind the click handler
            li.bind({
                'click': function(){
                    var marginLeft=i*options.pageWidth+i*options.itemMargin-2;

                    //set a bigger margin for IE6
                    if ($.browser.msie && $.browser.version.substr(0,1)<7) {
                        marginLeft+=i*options.itemMargin;
                    }
                    root.animate({marginLeft:[-marginLeft,options.easing]}, options.animationSpeed);

                    navUl.find('li.selected').removeClass('selected');
                    $(this).addClass('selected');
                },
                'mouseover':function(){
                    $(this).css({cursor:'pointer'});
                }
            });
        })(i);

        navUl.find('li:first').addClass('selected');

        //center the navigation
        var marginLeft=(options.pageWidth)/2-pageNumber*options.navButtonWidth/2;
        navUl.css({marginLeft:marginLeft});
    }
}

function setHoverFunctionality(){
    $('.portfolio_item').hover(function(){
        $(this).stop().animate({opacity:0.8}, 300);
    }, function(){
        $(this).stop().animate({opacity:1}, 300);
    });
}
};

因此,除了我已经实现的上述 javascript 代码中提供的所有自定义之外,设置类别单击事件处理程序的函数是displayCategories()从文件的第 117 行开始。这个函数的作用是从 XML 文件中设置的元素创建类别元素,它将类别 <li> 元素附加到父 <ul> 元素,并为它们设置点击处理程序。

再次查看我网站的画廊,在左侧边栏中,您可以在“所有艺术作品”下看到 HTML 按钮

这些是通过 CSS 精灵创建的总共 5 个按钮,我正在尝试使用它们而不是自定义 XML 标题来过滤类别!我尝试将左侧边栏留空并让图库代码自动创建链接。我在左侧边栏中创建了一个空的 <ul> 标记,并在 JS 文件的第 122 行分配了该标记的选择器:

var catUl=categoryHolder.find('ul');

这样代码就可以将类别链接附加到该 ul,我可以测试这是否可行。我在这里遇到了死胡同。

简而言之,我的问题是,是否有另一种更简单的方法可以通过 javascript 文件中的 HTML 锚定按钮或我可以创建以满足此要求的任何事件来调用类别?

您可能已经发现我不是 JS 专家,因此非常欢迎您的帮助。感谢和问候。PS:请询问 XML 或 JavaScript 文件中的任何代码,我会为您重新发布。

4

1 回答 1

0

如果不彻底修改插件,我看不到你可以在那里做很多事情。该插件正在为您完成所有 XML 解析,以及类别名称和它们的点击事件,虽然它们可以以不那么严重的方式插入/附加,但从它们各自的 XML 节点中提取值。要更改的所有内容都将涉及重新解析 XML,因此付出的努力似乎远大于回报。

于 2013-08-14T00:01:58.867 回答