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

网站导航栏:修复active函数失效并实现已访问元素变色

我来帮你搞定导航栏的这两个问题——先修复当前页面高亮失效的问题,再实现已访问链接标记为浅蓝色的功能:

一、修复当前页面Active高亮失效的问题

你原来的代码对比window.location.href和链接的href属性失效,主要是因为在预览环境中,完整URL会包含平台特定的域名、端口或参数,导致两者不匹配。我们可以改成只对比路径部分,这样更可靠:

修复后的Active函数(要放在DOM加载完成后执行):

$(document).ready(function() {
  $('a').each(function(){
    // 只对比路径部分,忽略域名、参数等差异
    if ($(this).prop('pathname') === window.location.pathname) {
      $(this).addClass('active');
      curpage = $(this).attr("title");
    }
  });
});

二、实现已访问链接标记为浅蓝色的功能

现代浏览器出于隐私保护,对CSS的:visited伪类限制很多(只能修改文字颜色,且无法通过JS读取访问状态),所以更灵活的方案是用localStorage记录用户访问过的链接,再给对应的元素添加样式:

步骤1:添加CSS样式

在style.css里新增:

/* 当前页高亮样式 */
.active {
  color: red !important;
}
/* 已访问链接样式 */
.visited {
  color: lightblue !important;
}

步骤2:完整JS代码(整合高亮和访问记录)

$(document).ready(function() {
  // 1. 处理当前页面高亮
  $('a').each(function(){
    if ($(this).prop('pathname') === window.location.pathname) {
      $(this).addClass('active');
      curpage = $(this).attr("title");
    }
  });

  // 2. 处理已访问链接标记
  // 从localStorage读取已访问列表,没有则初始化空数组
  let visitedLinks = JSON.parse(localStorage.getItem('visitedLinks')) || [];

  // 给已访问的链接添加样式
  $('a').each(function() {
    const linkHref = $(this).prop('href');
    if (visitedLinks.includes(linkHref)) {
      $(this).addClass('visited');
    }
  });

  // 监听链接点击,记录到localStorage(去重避免重复存储)
  $('a').on('click', function() {
    const linkHref = $(this).prop('href');
    if (!visitedLinks.includes(linkHref)) {
      visitedLinks.push(linkHref);
      localStorage.setItem('visitedLinks', JSON.stringify(visitedLinks));
    }
  });
});

补充说明

  • 如果你想用更简单的CSS方案(限制较多),可以直接写:
    a:visited {
      color: lightblue;
    }
    
    但注意这个样式会被w3.css的默认样式覆盖,所以可能需要加!important,且无法自定义背景、边框等样式,也无法通过JS控制哪些链接标记。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:36:16