构建当前以类别为中心的导航

I would like to develop a similar navigation to this website: http://www.enjukuracing.com/categories/nissan

They are on the BigCommerce platform and I like how their side navigation displays the categories and subcategories. Essentially I would like to know the logic in displaying something like this as well as what components in BigCommerce I would need to do this.

I’d like to point out a few things about this example that aren’t ideal to what we want.

  • This site seems to be suffering from multiple locations of the same link (if you look at the source, one link appears 4 times - my site is trying to avoid this because of upwards of 800+ internal links and also because of site load times to generate the navigation)
  • Each subcategory is generated for all the categories and different menu appearances—this is why they appear 4 times each

So ultimately, we’d want a navigation that does these things:

  • Know what category we are currently in
  • Display parent categories leading up to current category
  • Display sibling categories to current category
  • Display subcategory/children categories to current category
  • Expand down upon click to display children categories

I know the Category API can tell me the hierarchy of the categories, but I feel making AJAX calls to a PHP file on each page of my website might be counter-intuitive to making my website more speedy. Is there any simple object that I can access with JS that I can manipulate on a page-level?

I just did something like this using JS to figure out what categories to show/hide and which to have open/closed. First, include the category tree in your sidebar and hide it.

    function formatCustomSideBar(){
        var cats = [];
        $("ul.breadcrumbs > li").each(function(){
            if($(this).hasClass("is-active")){
                var name = $(this).find("span").text();
                cats.push(name);
            } else {
                var name = $(this).find("a").text();
                cats.push(name);
            }
        });
        console.log(cats);

        $(".custom-nav li a").each(function(){
            var subCat = $(this).text();
            if( $.inArray(subCat, cats) !== -1 ){
                $(this).parent("li").addClass("active-category");
            }
        });
    };
    formatCustomSideBar();

Next, add all breadcrumb values into an array because the breadcrumb always tells us where we are on the site. Then loop the navigation tree, and add a class of active-category to the list item if it is present in the breadcrumb array. Using the active-category class and CSS, you can style the feature.

To add the toggling functionality, I would add an additional few lines to the end of my function to loop list items with the active-category class, and check if they have a child <ul> to find out if they have children categories, and add a class like has-children from there.

Hope this helps.