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

Bootstrap 5 ScrollSpy功能正常但无法高亮,求问题排查

Bootstrap 5 ScrollSpy 导航项不高亮的解决方案

你的代码存在几个关键问题,导致ScrollSpy无法正确高亮导航项,以下是具体修复步骤:

1. 移除重复的Bootstrap JS引入

你在<head>和<body>末尾各引入了一次bootstrap.bundle.min.js,重复引入会引发脚本冲突,删掉<head>里的JS引入,只保留<body>末尾的那一份。

2. 二选一:统一ScrollSpy初始化方式

你同时使用了data属性自动初始化(滚动容器上的data-bs-spy="scroll")和JS手动初始化(new bootstrap.ScrollSpy(...)),两者冲突导致监听逻辑混乱,必须二选一:

选项A:用data属性自动初始化(推荐)

删掉手动初始化的JS代码:

var scrollSpy = new bootstrap.ScrollSpy(document.body, {
  target: '#navbar-example3'
});

然后给滚动容器添加固定高度和滚动属性,让ScrollSpy能正确监听容器内的滚动事件:

.scrollspy-example-2 {
  height: 400px; /* 根据页面需求调整高度 */
  overflow-y: auto;
}

选项B:用JS手动初始化

如果需要监听整个页面(body)的滚动,先移除滚动容器上的data-bs-spy="scroll"属性,再修改初始化代码的offset值,匹配你设置的scroll-padding-top: 100px:

var scrollSpy = new bootstrap.ScrollSpy(document.body, {
  target: '#navbar-example3',
  offset: 100
});

同时确保页面内容足够长,能触发滚动行为。

3. 删除重复的Bootstrap样式代码

你自定义的.nav、.nav-pills、.nav-link等样式和Bootstrap默认样式完全重复,不仅冗余,还可能因优先级问题导致.active类的高亮样式不生效,删掉<style>里这些重复的代码段,直接使用Bootstrap自带的类即可。

修正后的核心代码示例

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.2/font/bootstrap-icons.css">
  <title>UNITAYLE</title>
</head>
<style>
    html {
    scroll-padding-top: 100px; /* 匹配粘性导航栏高度 */
    }

    .unires {
        height: 18rem;
        object-fit: cover;
        width: 100%;
    }

    .scrollspy-example-2 {
        height: 400px;
        overflow-y: auto;
    }
</style>
<body>
    
    <?php include '../navsub.php'; ?>

    <!-- 页面头部内容不变 -->

    <div class="col-8">
        <div data-bs-spy="scroll" data-bs-target="#navbar-example3" data-bs-offset="100" data-bs-smooth-scroll="true" class="scrollspy-example-2" tabindex="0">
        <!-- 滚动内容不变 -->
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h255rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

</body>

最后确认:导航项的href属性值必须和目标元素的id完全一致(包括大小写),粘性导航栏的高度要和scroll-padding-top值匹配。

内容的提问来源于stack exchange,提问作者Sezer Selman Şenel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 18:47:16