为什么视差滚动不起作用?(Next.js Image + Tailwind)

7gs2gvoe  于 2022-12-03  发布在  其他
关注(0)|答案(2)|浏览(144)

我错过了什么,使视差滚动工作?

<div className="h-screen">
  <div className="relative h-full w-full bg-cover bg-fixed bg-center bg-no-repeat">
    <Image src="https://images.unsplash.com/photo-1454496522488-7a8e488e8606?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1955&q=80'" objectFit="cover" alt="test" layout="fill" priority={true} />
  </div>
</div>
xzlaal3s

xzlaal3s1#

要使视差滚动起作用,您需要将parallax属性添加到包含Image组件的div元素中,并将其值设置为您希望出现视差效果的速度。例如:

<div className="h-screen" parallax="0.5">
  <div className="relative h-full w-full bg-cover bg-fixed bg-center bg-no-repeat">
    <Image src="https://images.unsplash.com/photo-1454496522488-7a8e488e8606?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1955&q=80'" objectFit="cover" alt="test" layout="fill" priority={true} />
  </div>
</div>

parallax属性的值可以是0到1之间的任何数字,0表示没有视差效果,1表示最大视差效果。您选择的值将取决于您的个人喜好和网站的特定设计。您可能需要尝试不同的值以找到最佳的值。

nfeuvbwi

nfeuvbwi2#

我认为您应该将backGroundImage样式应用于使用bg-fixed类的div,而不是Image组件。
视差滚动是一种网页设计技术,其中网站的背景移动速度比前景慢。
如果您访问tailwindcss
用于控制背景图像在滚动时的行为的实用程序。

<div
        className="relative h-full w-full bg-cover  bg-center bg-fixed bg-no-repeat"
        style={{
          backgroundImage: `url(https://images.unsplash.com/photo-1454496522488-7a8e488e8606?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1955&q=80%27)`,
        }}
      ></div>

我创建了一个组件来测试它:

const Test = () => {
  return (
    <div className="h-screen">
      <div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
        Welcome to my site!
      </div>
      <div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
        Welcome to my site!
      </div>
      <div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
        Welcome to my site!
      </div>
      <div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
        Welcome to my site!
      </div>
      <div
        className="relative h-full w-full bg-cover  bg-center bg-fixed bg-no-repeat"
        style={{
          backgroundImage: `url(https://images.unsplash.com/photo-1454496522488-7a8e488e8606?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1955&q=80%27)`,
        }}
      ></div>
      <div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
        Welcome to my site!
      </div>
      <div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
        Welcome to my site!
      </div>
      <div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
        Welcome to my site!
      </div>
      <div className="p-5 text-2xl bg-purple-300 bg-opacity-50 rounded-xl">
        Welcome to my site!
      </div>
    </div>
  );
};

export default Test;

相关问题