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

如何用CSS和jQuery实现点击链接跳转同时移除下划线?

问题:实现导航链接跳转同时移除当前页面链接的下划线

我网页中有4个带<a>标签的导航链接,需求是:点击链接能正常跳转到对应页面,且当前页面的导航链接没有下划线。现有两种尝试的代码都存在问题:

  • Code A:能实现跳转,但无法移除当前页面链接的下划线
  • Code B:能移除链接下划线,但会导致链接无法跳转

下面是可行的解决方案Code C示例:


Code A(可跳转但无法移除下划线)

$(function () {
    $(".mainMenu").click(function () {
        $(".mainMenu").removeClass("mainMenuSelected").addClass("mainMenu");        
        $(this).addClass("mainMenuSelected");
    });
});
<a id="id_home"  href="/Default.aspx"  class="mainMenu" >Home</a>
<a id="id_demo"  href="/Demo.aspx"  class="mainMenu">Demo</a>
<a id="id_help"  href="/Help.aspx"  class="mainMenu">Help</a>
<a id="id_about" href="/About.aspx"  class="mainMenu">About</a>
.mainMenu {
    font-size: 20px;
    margin-right: 25px;    
}

.mainMenuSelected {
    text-decoration: none;
    color: Blue;
}

Code B(可移除下划线但无法跳转)

$(function () {
    $(".mainMenu").click(function () {
        $(".mainMenu").removeClass("mainMenuSelected").addClass("mainMenu");        
        $(this).removeAttr("href").addClass("mainMenuSelected");
    });
});

HTML和CSS部分与Code A完全一致


Code C(可行方案)

$(function () {
    var filename = window.location.pathname.split('/').pop();

    switch (filename.toUpperCase()) {
        case "Default.aspx".toUpperCase():
            setMainMenuSelected("#id_home");
            break;

        case "":
            setMainMenuSelected("#id_home");
            break;

        case "Demo.aspx".toUpperCase():
            setMainMenuSelected("#id_demo");
            break;

        case "Help.aspx".toUpperCase():
            setMainMenuSelected("#id_help");
            break;

        case "About.aspx".toUpperCase():
            setMainMenuSelected("#id_about");
            break;

    }

});

function setMainMenuSelected(id) {
    $(id).removeAttr("href").addClass("mainMenuSelected");
}

方案说明

Code C的核心逻辑是页面加载时自动识别当前页面对应的导航链接:

  1. 通过window.location.pathname获取当前页面路径,提取文件名
  2. 根据文件名匹配对应的导航链接ID,调用setMainMenuSelected函数
  3. 该函数会移除目标链接的href属性(避免重复跳转)并添加mainMenuSelected样式(去掉下划线)
  4. 其他未匹配的链接保留href属性,点击可正常跳转到对应页面

当用户跳转到新页面后,新页面加载时会重复上述判断,自动给当前页面的导航链接应用无下划线样式,完美满足「跳转功能+当前页面链接无下划线」的需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:52:31