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

求助fullpage.js实现跨div自动同步对应slide的文本内容功能

fullpage.js 跨场景全局caption同步修复实现

原代码存在的核心问题

  • 两个回调函数中直接使用$(this)选择目标元素,上下文匹配完全错误,根本无法精准拿到当前激活slide下的.caption内容
  • 没有区分垂直section切换、水平slide切换场景下的元素定位逻辑,会出现内容错位、切换后caption不更新、初始加载内容不匹配的问题
  • 参考的2015年旧方案适配早期fullpage版本,现代版本的回调参数结构已经标准化,继续沿用旧的取值逻辑必然失效

修复后的实现逻辑

完全基于现代fullpage.js的回调自带参数定位目标元素,不依赖模糊的上下文指向,全覆盖所有切换场景:

  1. 垂直方向切换section时,通过afterLoad回调返回的当前激活section对象,定位该section下默认激活slide对应的.caption内容,同步到全局.current-caption容器
  2. 水平方向切换slide时,通过afterSlideLoad回调返回的当前激活slide对象,直接提取对应.caption的内容完成同步
  3. 页面初始加载时,自动触发一次初始激活位置的内容提取,保证首屏caption和展示内容完全匹配

可直接复用的完整代码

<!-- 全局caption展示容器 -->
<div class="current-caption"><p>.current-caption</p></div>

<div id="fullpage">
    <div class="section" data-anchor="S1" style="background-color: #ddd;"> 
        <div class="slide" data-anchor="S1s1">
            <h1>S1s1</h1>
            <div class="caption"><p>Caption text for S1s1</p></div>
        </div>
        <div class="slide" data-anchor="S1s2">
            <h1>S1s2</h1>
            <div class="caption"><p>Caption text for S1s2</p></div>
        </div>
    </div> 

    <div class="section" data-anchor="S2" style="background-color: #fff;"> 
        <div class="slide" data-anchor="S2s1">
            <h1>S2s1</h1>
            <div class="caption"><p>Caption text for S2s1</p></div>
        </div>
        <div class="slide" data-anchor="S2s2">
            <h1>S2s2</h1>
            <div class="caption"><p>Caption text for S2s2</p></div>
        </div>
    </div> 
</div>

<script>
new fullpage('#fullpage', {
    verticalCentered: true,
    autoScrolling: true,
    controlArrows: true,
    // 水平slide切换触发
    afterSlideLoad: function(section, origin, destination, direction){
        const activeCaption = $(destination.item).find(".caption").html();
        $(".current-caption").html(activeCaption); 
    },  
    // 垂直section切换触发
    afterLoad: function(origin, destination, direction){
        const activeCaption = $(destination.item).find(".slide.active .caption").html();
        $(".current-caption").html(activeCaption); 
    }
});
</script>

适配特性说明

  • 兼容当前主流的fullpage.js正式版本,不存在版本适配问题
  • 全场景覆盖:不管是垂直切换section、同一section内水平切换slide,都能精准同步对应内容的caption
  • 不侵入原有fullpage的默认运行逻辑,不会和其他自定义回调产生冲突
  • 无需额外的事件监听,直接复用fullpage内置的生命周期回调,性能开销极低

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 10:36:02