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

react-intersection-observer移动端视图不生效问题咨询

修复方案

核心问题原因

  1. 固定阈值threshold:0.2不兼容移动端纵向堆叠布局,移动端下HeroSection高度更高,很难满足20%面积进入视口的触发条件
  2. 未给motion组件设置initial属性,移动端渲染时初始状态未正确初始化为隐藏,导致动画触发无前后状态差
  3. 隐藏状态x轴偏移x:-1000为固定像素值,小屏移动设备下元素直接被移出可观测范围,交叉观测器无法检测到元素存在
  4. 冗余的useAnimation+useEffect逻辑容易出现状态同步异常,增加不必要的渲染负担

修复后完整代码

import Image from "next/image";
import { useRouter } from "next/router";
import { motion } from "framer-motion";

import profile from "../images/profile.jpg";
import { useInView } from "react-intersection-observer";

const HeroSection = () => {
    const router = useRouter();
    // 调整观测配置适配移动端
    const { ref, inView } = useInView({
        threshold: 0,
        rootMargin: '0px 0px -50px 0px', // 元素进入视口50px即触发
        triggerOnce: true // 仅触发一次动画可保留,需要滚动反复触发可删除
    });

    const heroAnimation = {
        hide: {
            x: '-100vw', // 改为相对视口宽度的偏移,适配不同屏幕尺寸
            opacity: 0,
        },
        show: {
            x: 0,
            opacity: [0.1, 1],
            transition: { delay: 0.3, duration: 0.75, type: "spring", bounce: 0.2 },
        },
    };

    return (
        <motion.div
            initial="hide" // 补充初始状态
            animate={inView ? "show" : "hide"} // 直接用inView控制动画,省略冗余逻辑
            variants={heroAnimation}
            ref={ref}
            className='space-y-10 px-4 flex flex-col md:grid md:grid-cols-2 md:py-12 bg-white pb-[50px]'>
            <div className='flex flex-col justify-center items-center space-y-10'>
                <h1 className='text-5xl mt-[50px] md:mt-0'>Welcome!</h1>
                <p className='text-center max-w-[400px] lg:max-w-[650px]'> website intro
                </p>
                <button
                    onClick={() => router.push("/about")}
                    className='bg-gray-200 shadow-md text-gray-700 font-bold p-3 lg:p-4 rounded-lg active:bg-gray-300 active:shadow-lg hover:scale-105 transition duration-200 ease-in-out'>
                    READ MORE..
                </button>
            </div>

            <div className='rounded-lg relative m-auto h-[350px] w-[280px] md:h-[400px] md:w-[320px] lg:h-[500px] lg:w-[400px]'>
                <Image
                    className='rounded-lg'
                    objectFit='contain'
                    layout='fill'
                    src={profile}
                    alt='profile'
                />
            </div>
        </motion.div>
    );
};

export default HeroSection;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:48:01