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

滚动时切换固定文本颜色的JS实现方案咨询

实现滚动切换固定文本颜色的JavaScript示例

基础HTML结构参考

<!-- 固定导航/文本元素 -->
<div class="fixed-elements">
  <span class="site-name">你的名称</span>
  <button class="action-btn">联系我</button>
</div>

<!-- 页面各区块 -->
<section class="section section-light">首页</section>
<section class="section section-dark">关于我</section>
<section class="section section-light">作品集</section>
<section class="section section-dark">联系方式</section>

配套CSS样式

.fixed-elements {
  position: fixed;
  top: 20px;
  left: 20px;
  z-index: 999;
}

/* 定义不同文本颜色类 */
.text-light { color: #ffffff; }
.text-dark { color: #1a1a1a; }

/* 区块样式,确保占满视口高度方便测试 */
.section {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
}
.section-light { background-color: #ffffff; }
.section-dark { background-color: #1a1a1a; color: #fff; }

JavaScript实现代码

// 获取固定元素和所有区块
const fixedElements = document.querySelector('.fixed-elements');
const sections = document.querySelectorAll('.section');

// 使用IntersectionObserver监听区块可见性
const observerOptions = {
  root: null, // 视口作为根元素
  rootMargin: '-50% 0px -50% 0px', // 当区块垂直中心进入视口时触发
  threshold: 0
};

const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      // 根据当前区块的类判断需要切换的文本颜色
      if (entry.target.classList.contains('section-dark')) {
        fixedElements.classList.add('text-light');
        fixedElements.classList.remove('text-dark');
      } else {
        fixedElements.classList.add('text-dark');
        fixedElements.classList.remove('text-light');
      }
    }
  });
}, observerOptions);

// 为每个区块添加监听
sections.forEach(section => {
  observer.observe(section);
});

关键说明

  • 使用IntersectionObserver替代传统scroll事件监听,性能更优,不会因高频滚动导致页面卡顿
  • rootMargin设置为-50% 0px -50% 0px,意味着当区块垂直中心点进入视口时触发切换逻辑,确保颜色切换时机精准
  • 可根据需求调整rootMargin值,或者修改触发条件(比如区块顶部进入视口时切换)
  • 如果区块有自定义主题色,可改用自定义属性提升扩展性:
    <section class="section" data-text-color="light">...</section>
    
    对应JS逻辑修改为:
    const targetColor = entry.target.dataset.textColor;
    fixedElements.className = `fixed-elements text-${targetColor}`;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:05:17