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

基于Lenis平滑滚动与Framer Motion实现横向滚动Div吸附定位

解决Lenis+Framer Motion环境下横向滚动区域的自动停靠问题

一、先排查CSS Scroll Snap的配置与冲突问题

CSS Scroll Snap失效大概率是配置不全或与Lenis/Framer Motion的行为冲突,先确认以下配置是否到位:

1. 滚动容器与卡片的正确CSS设置

确保滚动容器和卡片的核心样式正确,缺一不可:

/* 横向滚动容器 */
.scroll-container {
  overflow-x: auto;
  overflow-y: hidden; /* 禁止纵向滚动,避免干扰 */
  scroll-snap-type: x mandatory; /* mandatory 强制停靠,proximity 接近时停靠 */
  height: 100vh; /* 设置固定高度,确保滚动轴正确 */
  /* 禁用Framer Motion或Lenis可能添加的transform,避免破坏scroll snap上下文 */
  transform: none !important;
}

/* 滚动卡片 */
.scroll-card {
  scroll-snap-align: start; /* 可选:center/end,根据停靠位置需求 */
  flex-shrink: 0; /* 禁止卡片收缩,保证宽度一致 */
  width: 100vw; /* 卡片宽度匹配容器视口,确保每次停靠完整显示 */
  height: 100%;
}

2. 解决Lenis的滚动劫持冲突

Lenis的平滑滚动会劫持原生scroll事件,导致CSS Scroll Snap无法触发。需要将横向滚动容器排除在Lenis的控制之外:

  • 原生Lenis初始化时添加排除规则:
const lenis = new Lenis({
  exclude: (element) => element.classList.contains('scroll-container')
})
  • React环境下使用@studio-freight/react-lenis,直接给容器加属性:
<div className="scroll-container" data-lenis-prevent>
  {/* 卡片列表 */}
</div>

二、Framer Motion粘性容器的注意事项

如果你的横向区域是用Framer Motion实现粘性效果(比如useScroll+useTransform),需注意:

  • 粘性容器的父元素不能设置overflow: hidden,否则会切断scroll snap的上下文
  • 不要给滚动容器或卡片添加不必要的transform属性(Framer Motion动画可能自动添加),这会让scroll snap失效
  • 确保scroll-snap-align是加在卡片元素本身,而非外层的motion容器上

三、JS方案替代(react-use-scroll-snap)

如果CSS方案仍不生效,尝试用react-use-scroll-snap实现JS控制的停靠,同时必须排除Lenis对该容器的控制:

import { useRef } from 'react';
import { useScrollSnap } from 'react-use-scroll-snap';

const HorizontalScrollSection = () => {
  const containerRef = useRef(null);

  useScrollSnap({
    element: containerRef.current,
    direction: 'x',
    snapAlign: 'start',
    duration: 300, // 停靠动画时长,适配平滑滚动
  });

  return (
    <div 
      ref={containerRef} 
      className="scroll-container" 
      data-lenis-prevent // 强制排除Lenis控制
    >
      {/* 你的项目卡片列表 */}
      <div className="scroll-card">项目1</div>
      <div className="scroll-card">项目2</div>
    </div>
  );
};

四、快速排查清单

  1. 检查浏览器控制台是否有CSS警告,确认scroll-snap-type等属性是否被正确解析
  2. 临时禁用Lenis和Framer Motion的效果,测试原生CSS Scroll Snap是否正常工作,定位冲突来源
  3. 确保滚动容器没有被其他元素的z-index或定位属性遮挡,导致滚动事件无法触发

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 05:12:37