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

如何使用load()加载内容时保持页面滚动位置或定位到指定元素

解决load()刷新后页面滚动位置丢失的问题

方案一:保存并恢复滚动位置

在触发load前记录当前页面的滚动距离,加载完成后直接恢复该位置,避免页面跳回顶部:

$('.options input').click(function(){
    // 记录当前滚动位置
    const currentScroll = $(window).scrollTop();
    $('.filter-wrapper').load('index.php?route=product/filter&path=<?php echo $path ?>'+selected_filters, function(){
        // 加载完成后恢复滚动位置
        $(window).scrollTop(currentScroll);
    });
})

注:原代码中的选择器.option input应为.options input,对应HTML里的<div class="options">容器

方案二:定位到点击的筛选分组锚点

如果需要点击某分组的复选框后,页面自动定位到该分组的锚点(比如Height组的#126),可以通过获取当前复选框所属分组的锚点ID,加载完成后直接滚动到对应位置:

$('.options input').click(function(){
    // 获取当前复选框所在分组的锚点链接
    const targetAnchor = $(this).closest('.group').find('a').attr('href');
    $('.filter-wrapper').load('index.php?route=product/filter&path=<?php echo $path ?>'+selected_filters, function(){
        // 加载完成后滚动到目标锚点
        if(targetAnchor){
            $(targetAnchor)[0].scrollIntoView({
                behavior: 'smooth', // 平滑滚动,可根据需求移除
                block: 'start'
            });
        }
    });
})

这个方案更贴合精准定位需求,用户操作后能直接回到对应的筛选组位置,体验更友好。

额外优化:避免意外默认行为

如果存在父元素的默认事件干扰,可在点击事件中阻止默认行为,确保逻辑正常执行:

$('.options input').click(function(event){
    event.preventDefault();
    const targetAnchor = $(this).closest('.group').find('a').attr('href');
    $('.filter-wrapper').load('index.php?route=product/filter&path=<?php echo $path ?>'+selected_filters, function(){
        if(targetAnchor){
            $(targetAnchor)[0].scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }
    });
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 04:45:43