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

如何实现fullPage.js页面中固定块随屏幕切换更改背景色?

嘿,这个需求用fullPage.js自带的回调函数就能轻松搞定,我给你一步步拆解怎么实现:

核心思路

fullPage.js提供了afterLoad回调函数——每次滚动切换到新的section并加载完成后,这个函数就会触发。我们可以在这个回调里,根据当前激活的section动态修改.fixed元素的背景色。

具体实现方案

方案一:用颜色数组对应section索引

这种方式适合颜色固定、和section顺序一一对应的场景:

完整代码

<div class="fixed"></div>
<div id="fullpage">
  <div class="section"></div>
  <div class="section"></div>
  <div class="section"></div>
</div>

<style>
.fixed {
  width: 120px;
  height: 120px;
  position: fixed;
  top: 30px;
  left: 30px;
  z-index: 9999;
  transition: background-color 0.3s ease; /* 加个过渡动画更丝滑 */
}

.section {
  height: 100vh; /* 让每个section占满屏幕 */
}
</style>

<script>
// 初始化fullPage并配置回调
new fullpage('#fullpage', {
  // 定义每个section对应的背景色,顺序和section一一对应
  sectionColors: ['#f0f0f0', '#2c3e50', '#e74c3c'],
  afterLoad: function(origin, destination, direction) {
    // 获取当前section的索引(v3版本是0开始,v2版本是1开始,注意对应)
    const currentIndex = destination.index;
    // 拿到对应颜色并设置给fixed块
    document.querySelector('.fixed').style.backgroundColor = this.sectionColors[currentIndex];
  }
});
</script>

方案二:用data属性自定义每个section的颜色

这种方式更灵活,后期要改颜色直接在HTML里修改就行,不用动JS:

完整代码

<div class="fixed"></div>
<div id="fullpage">
  <div class="section" data-bgcolor="#ffcc00"></div>
  <div class="section" data-bgcolor="#3498db"></div>
  <div class="section" data-bgcolor="#9b59b6"></div>
</div>

<style>
/* 样式和方案一一致 */
.fixed {
  width: 120px;
  height: 120px;
  position: fixed;
  top: 30px;
  left: 30px;
  z-index: 9999;
  transition: background-color 0.3s ease;
}

.section {
  height: 100vh;
}
</style>

<script>
new fullpage('#fullpage', {
  afterLoad: function(origin, destination, direction) {
    // 从当前激活的section上拿到自定义的颜色值
    const targetColor = destination.item.dataset.bgcolor;
    // 设置给fixed块
    document.querySelector('.fixed').style.backgroundColor = targetColor;
  }
});
</script>
注意点
  • 如果你用的是fullPage.js旧版本(比如v2),afterLoad的参数格式会有差异,旧版本参数是anchorLink, index,索引从1开始,需要调整代码逻辑对应颜色数组。
  • 给.fixed加过渡动画能让颜色切换更平滑,避免突兀感。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:56:19