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

如何利用FullPage JS的onLeave函数动态切换元素CSS样式

解决fullPage.js切换section过程中动态修改指定类样式的问题

你的核心问题在于当前onLeave函数里同时对所有.dark元素执行了添加和移除遮罩的操作——代码是同步执行的,后一行会直接覆盖前一行的效果,所以根本看不到预期的遮罩变化。我们需要针对当前要离开的section和即将进入的section的.dark元素分别操作,利用index、nextIndex甚至fullPage.js提供的DOM参数来精准定位元素。

修正后的基础实现代码

onLeave: function(index, nextIndex, direction){
    // 定位当前要离开的section内的.dark元素,添加颜色遮罩
    $(`#section${index-1} .dark`).css("background-color","rgba(0,0,0,.55)");
    // 定位即将进入的section内的.dark元素,移除颜色遮罩
    $(`#section${nextIndex-1} .dark`).css("background-color","rgba(0,0,0,0)");
}

为什么这样可行?

  • fullPage.js的section索引是从1开始计数的,但你的section ID是section0、section1这种从0开始的命名,所以需要用index-1和nextIndex-1来匹配对应的DOM元素ID。
  • onLeave触发时正是section切换的过渡过程中,此时分别操作两个section的.dark元素,就能实现“当前section加遮罩淡出、下一个section无遮罩淡入”的预期效果。

更灵活的优化方案(推荐)

如果未来你的section数量可能变化,或者不想依赖固定的ID命名,可以直接使用fullPage.jsonLeave回调提供的currentSection和nextSectionDOM参数来定位元素,扩展性更强:

onLeave: function(index, nextIndex, direction, currentSection, nextSection){
    // 直接操作当前section内的.dark元素
    $(currentSection).find(".dark").css("background-color","rgba(0,0,0,.55)");
    // 直接操作下一个section内的.dark元素
    $(nextSection).find(".dark").css("background-color","rgba(0,0,0,0)");
}

进阶维护建议:用CSS类替代行内样式

直接修改行内样式不利于代码维护,推荐把遮罩效果写成CSS类,通过添加/移除类来控制样式,还能配合过渡动画让效果更平滑:

/* 基础样式 */
.dark {
    background-color: rgba(0,0,0,0);
    transition: background-color 0.3s ease; /* 添加强制过渡动画 */
}
/* 遮罩样式 */
.dark.mask-active {
    background-color: rgba(0,0,0,.55);
}
onLeave: function(index, nextIndex, direction, currentSection, nextSection){
    $(currentSection).find(".dark").addClass("mask-active");
    $(nextSection).find(".dark").removeClass("mask-active");
}

这种方式不仅代码结构更清晰,还能让遮罩的切换过程更自然,提升整体页面的交互质感。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:15:02