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

点击锚点链接时如何隐藏浏览器地址栏显示的#锚点后缀

实现方案

要隐藏地址栏的锚点后缀,只需要通过JavaScript拦截a标签的默认点击行为,手动实现滚动逻辑即可,不需要修改现有HTML和CSS结构。

操作步骤

  1. 找到现有HTML代码里的<script>标签,在现有代码后追加如下JS代码:
// 处理导航栏内锚点点击
document.querySelectorAll('.page-scroll a').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        // 阻止默认锚点跳转,避免URL生成hash后缀
        e.preventDefault();
        // 读取href属性对应的目标元素ID
        const targetId = this.getAttribute('href').slice(1);
        const targetEl = document.getElementById(targetId);
        if (!targetEl) return;
        // 滚动到目标位置,不需要平滑效果可删除`behavior: 'smooth'`配置
        window.scrollTo({
            top: targetEl.offsetTop,
            behavior: 'smooth'
        });
    });
});

// 可选:处理logo点击回到顶部,避免地址栏出现#
document.querySelector('a.logo').addEventListener('click', e => {
    e.preventDefault();
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
});
  1. 保存代码刷新页面即可生效,点击锚点链接时地址栏不会再出现#后缀的锚点标识。

补充说明

  • 该方案完全复用你现有用来做头部偏移的dummy元素,不需要调整页面布局结构
  • 如果不需要平滑滚动效果,删除配置项里的behavior: 'smooth'即可实现和原生锚点一致的瞬间跳转效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:54:08