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

Next.js开发中遇`position: fixed`导致自动滚动跳过警告的问题

解决Next.js中「Skipping auto-scroll behavior due to position: sticky or fixed css」警告

这个警告是因为Next.js默认的路由跳转/组件挂载自动滚动逻辑,遇到position: fixed或sticky的元素时会跳过执行,避免滚动行为与脱离文档流的元素冲突。针对你的移动端侧边栏代码,提供以下几种解决方式:

方法一:手动控制路由跳转后的滚动行为

如果需要保留页面跳转后回到顶部的效果,可通过监听路由事件手动触发滚动:

import { useEffect } from 'react';
import { useRouter } from 'next/router';

const YourSidebarComponent = ({ showMenu }) => {
  const router = useRouter();

  useEffect(() => {
    const handleRouteComplete = () => {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    };

    router.events.on('routeChangeComplete', handleRouteComplete);
    // 组件卸载时移除监听
    return () => router.events.off('routeChangeComplete', handleRouteComplete);
  }, [router]);

  return (
    <aside className={`site-off desktop-hide ${showMenu ? "show-menu" : ""}`}>
      {/* 侧边栏内容 */}
    </aside>
  );
};

export default YourSidebarComponent;

方法二:关闭Next.js全局自动滚动恢复

如果你的项目不需要Next.js默认的滚动位置恢复功能,可在配置文件中禁用:

// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  scrollRestoration: false,
};

module.exports = nextConfig;

方法三:优化侧边栏自身滚动逻辑

你的侧边栏设置了overflow-y: auto,可添加属性确保滚动容器独立,减少与全局滚动的冲突:

.site-off {
    position: fixed;
    width: 320px;
    height: 100vh; /* 替换var(--percent100)为100vh更明确 */
    background-color: var(--white-color);
    overflow-y: auto;
    z-index: 1000;
    transform: translateX(-100%);
    visibility: hidden;
    transition: transform 0.4s, visibility 0.4s;
    will-change: transform, visibility;
    /* 添加以下属性隔离滚动 */
    overscroll-behavior: contain;
}

内容的提问来源于stack exchange,提问作者Khuong Viet Tai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 18:52:11