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

FullpageJS(jQuery版)Window.scrollTo失效,滚动定位问题求助

问题

我正在使用fullPage.js的jQuery版本,页面包含4个垂直section,其中第三个section内容较长(已开启scrollOverflow: true)。需求是点击该section内的列表项时,根据列表项的offsetTop调整滚动位置,但window.scrollTo()完全无效。我尝试了直接修改.fp-scroller和.iScrollIndicator的transform属性,但计算结果总是不准确,显然这不是正确的解决办法:

let elem = document.querySelector(".active");
$('.active-section .fp-scroller').css({'transform': `translate(0, -${elem.offsetTop}px)`});
$('.active-section .iScrollIndicator').css({'transform': `translate(0, ${ $('.active-section').height() - elem.offsetTop }px)`});

相关代码结构如下:

<div class="wrapper">
   <section class="section one"> One </section>
   <section class="section two"> two </section>
   <section class="section three"> three - (这里包含多个<li>列表项)</section>
   <section class="section four"> four </section>
</div>
$('li').click( function(){
    let ind = $('.animate-section.active').index();
    $.fn.fullpage.reBuild();
    $.fn.fullpage.silentMoveTo(ind + 1);

    $('li').removeClass('active');
    $(this).addClass('active');

    let elem = document.querySelector(".active");
    $('.active-section .fp-scroller').css({'transform': `translate(0, -${elem.offsetTop}px)`});
    $('.active-section .iScrollIndicator').css({'transform': `translate(0, ${ $('.active-section').height() - elem.offsetTop }px)`});
 });

$('.wrapper').fullpage({
        sectionSelector: '.section',
        navigation: false,
        normalScrollElements: '', // 原代码存在语法错误,需补充值
        scrollOverflow: true,
        onLeave: function (origin, destination, direction, trigger) {
            
        },
        afterLoad: function (origin, destination, direction, trigger) {
           
        },
    });

解决方案

当fullPage开启scrollOverflow: true时,长内容section的滚动由内部的iScroll实例管理,而非浏览器原生滚动,因此window.scrollTo()不会生效。必须通过fullPage暴露的iScroll实例来操作滚动:

  1. 修复语法错误
    原配置中normalScrollElements:后缺少值,补充为空字符串''(无需指定元素时)。

  2. 通过iScroll实例滚动到目标元素
    fullPage会为每个开启scrollOverflow的section创建iScroll实例,存储在$.fn.fullpage.iScrolls数组中(数组索引从0开始,对应section的顺序)。修改点击事件代码如下:

$('li').click(function() {
    // 静默切换到第三个section(fullpage的section索引从1开始)
    $.fn.fullpage.silentMoveTo(3);

    $('li').removeClass('active');
    $(this).addClass('active');

    // 获取第三个section对应的iScroll实例(数组索引为2)
    const iscrollInstance = $.fn.fullpage.iScrolls[2];
    
    if (iscrollInstance) {
        // 调用iScrollAPI滚动到目标li元素,500为动画时长(可选)
        iscrollInstance.scrollToElement($(this)[0], 500);
    }
});
  1. 原方法无效的原因
    直接修改transform会和iScroll的内部状态冲突,iScroll会自动覆盖手动设置的transform值,导致滚动位置不准。必须使用iScroll提供的API操作,才能保证滚动状态同步。

  2. 额外注意

  • 若section内容动态变化,需调用$.fn.fullpage.reBuild()重新初始化iScroll,建议将滚动逻辑放在afterLoad回调或延迟执行(如setTimeout),确保实例已重建完成。
  • 操作前可判断$.fn.fullpage.iScrolls数组及对应索引的实例是否存在,避免报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:31:02