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

分类链接追加分页等后缀时,如何保留分类激活选中样式?

问题根源

你当前的激活逻辑是完全匹配当前页面完整URL和导航a标签的href属性,当切换分页后URL会新增分页参数、路径后缀等内容,无法和原分类的href完全匹配,就会导致激活样式丢失。

解决方案

把完全匹配的逻辑调整为「检查当前URL是否以分类链接的href为前缀」即可,适配各种分页后缀场景:

$(document).ready(function() {
    const currentUrl = window.location.href;
    $('.cateBox li a').each(function() {
        const cateLink = this.href;
        // 非首页分类:只要当前URL以分类链接开头就匹配
        if (currentUrl.indexOf(cateLink) === 0) {
            $(this).parent()
                .addClass('active')
                .parent().parent().addClass('active');
            return false;
        }
    });
});

特殊场景适配(可选)

如果你的首页导航指向index.html,不希望首页导航被所有页面匹配,可以单独增加首页的判断逻辑:

$(document).ready(function() {
    const currentUrl = window.location.href;
    $('.cateBox li a').each(function() {
        const cateLink = this.href;
        // 首页单独判断,仅实际打开首页时激活
        if (cateLink.includes('index.html')) {
            const rootUrl = cateLink.replace('index.html', '');
            if (currentUrl === cateLink || currentUrl === rootUrl) {
                $(this).parent()
                    .addClass('active')
                    .parent().parent().addClass('active');
            }
        } 
        // 其他分类按前缀匹配
        else if (currentUrl.indexOf(cateLink) === 0) {
            $(this).parent()
                .addClass('active')
                .parent().parent().addClass('active');
            return false;
        }
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 06:54:02