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

如何让Scroll Indicator点击后保持橙色激活状态?

解决滚动指示器圆点点击后保持橙色高亮的问题

核心问题是你之前用的伪类没法持久化点击状态,得通过添加自定义激活类来实现,结合jQuery控制类的切换,同时处理滚动同步更新状态。

步骤说明

  1. 给每个滚动指示器圆点添加data-target属性,关联对应的section区块ID
  2. 在CSS中定义.active类,设置橙色高亮样式
  3. 用jQuery处理两个逻辑:
    • 点击圆点时,切换激活类并滚动到目标section
    • 页面滚动时,根据当前可视的section自动更新指示器的激活状态

修改后的完整代码

HTML

<!-- 滚动指示器 -->
<div class="scroll-indicator">
  <span class="dot active" data-target="#section1"></span>
  <span class="dot" data-target="#section2"></span>
  <span class="dot" data-target="#section3"></span>
</div>

<!-- 页面区块 -->
<section id="section1">第一区块内容</section>
<section id="section2">第二区块内容</section>
<section id="section3">第三区块内容</section>

CSS

.scroll-indicator {
  position: fixed;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #ccc; /* 默认灰色 */
  cursor: pointer;
  transition: background-color 0.3s ease;
}

/* 激活状态的橙色样式 */
.dot.active {
  background-color: #ff7f24; /* 橙色 */
}

/* 页面区块样式(示例) */
section {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

#section1 { background-color: #f0f0f0; }
#section2 { background-color: #e0e0e0; }
#section3 { background-color: #d0d0d0; }

jQuery

$(document).ready(function() {
  // 点击圆点的处理逻辑
  $('.dot').click(function() {
    // 移除所有圆点的active类
    $('.dot').removeClass('active');
    // 给当前点击的圆点添加active类
    $(this).addClass('active');
    // 获取目标section的ID并滚动到对应位置
    const target = $(this).data('target');
    $('html, body').animate({
      scrollTop: $(target).offset().top
    }, 500);
  });

  // 页面滚动时自动更新指示器状态
  $(window).scroll(function() {
    const scrollPos = $(window).scrollTop() + $(window).height() / 2; // 取视口中间位置判断

    $('section').each(function() {
      const sectionTop = $(this).offset().top;
      const sectionBottom = sectionTop + $(this).outerHeight();
      const sectionId = '#' + $(this).attr('id');

      // 如果滚动位置在当前section范围内
      if (scrollPos >= sectionTop && scrollPos <= sectionBottom) {
        // 更新指示器的active类
        $('.dot').removeClass('active');
        $('.dot[data-target="' + sectionId + '"]').addClass('active');
      }
    });
  });
});

为什么之前的方法无效?

  • :visited伪类仅适用于<a>标签的已访问链接状态,对普通<span>圆点完全不起作用
  • ::before/::after是伪元素,用来添加装饰性内容,无法用来保存或切换元素的激活状态
  • 只有通过添加/移除自定义类的方式,才能持久化控制元素的样式状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:55:18