You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用分页时如何保持gallery导航All项的active类激活状态

适配分页场景的图库导航active类设置方案

你原来的代码使用全等匹配URL,只有当前URL和导航href完全一致时才会加active类,分页URL多了/page/xx/后缀,自然匹配失效。调整后的代码如下,不仅能满足All分类分页时的高亮需求,还能同时兼容各个子分类的分页高亮:

jQuery(function($) {
    // 获取当前页面的路径(仅保留域名后的部分,排除查询参数、锚点干扰)
    const currentPath = window.location.pathname;
    // 先清空所有导航的active类,避免样式冲突
    $('.gallery_listing_wrapper li a').removeClass('active');

    let matchedSubCategory = false;
    // 优先匹配子分类导航
    $('.gallery_listing_wrapper li a:not([href="/gallery/"])').each(function() {
        const navBasePath = new URL(this.href).pathname;
        // 当前路径以分类导航路径为前缀,说明属于该分类(包含分类下的所有分页)
        if (currentPath.startsWith(navBasePath)) {
            $(this).addClass('active');
            matchedSubCategory = true;
            return false; // 匹配到对应分类后终止循环
        }
    });

    // 未匹配到任何子分类、且路径属于图库页面范围时,给All导航加active
    if (!matchedSubCategory && currentPath.startsWith('/gallery/')) {
        $('.gallery_listing_wrapper li a[href="/gallery/"]').addClass('active');
    }
});

代码逻辑说明

  • 改用pathname做匹配,过滤了域名、查询参数、锚点的影响,匹配稳定性更高
  • 先遍历子分类导航,只要当前页面属于该分类下的内容(包括分页)就触发高亮,自动覆盖子分类分页场景
  • 没有匹配到子分类时,所有/gallery/路径下的页面(包括/gallery/page/2/这类All分类的分页)都会给All导航项加active,完全匹配你的需求

内容的提问来源于stack exchange,提问作者Joshua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 10:54:03