【问题标题】:How would I achieve this scroll background colour change effect?我将如何实现这种滚动背景颜色变化效果?
【发布时间】:2022-07-29 17:30:50
【问题描述】:

基本上,假设我有 10 个部分。每个都分配了不同的颜色作为背景颜色。

当用户从第 1 部分向下滚动到第 10 部分时,我希望标签背景颜色相应地更改,具体取决于屏幕上的部分。

假设视口的高度为 1000px,我希望该函数找出 1000px 中当前位于 800px 的部分,即底部 20%,然后在底部 20% 中找到该部分的背景颜色和将其应用于标签,直到用户滚动到下一部分,或者向上滚动并且另一个组件接管背景颜色。

我曾尝试为此使用 IntersectionObservor,但我认为这不是我想要的最佳方法。

目前,我的设置是,我正在渲染多个组件,每个组件都有一个数据属性“data-background={background}”

然后,观察者循环遍历,将它们全部添加到观察者中,并观察以找到屏幕上显示的是哪一个,但它并不能完全满足我的需要。

有没有更简单的方法来实现我正在寻找的东西?

这是我目前的代码

import Page from "../components/common/Page";
import Hero from "../components/molecules/Hero";
import TechStack from "@/components/organisms/TechStack";
import { useEffect } from "react";

const Home = () => {
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          console.log("entry", entry);
          if (entry.isIntersecting) {
            document.body.style.backgroundColor =
              entry.target.dataset.background;
          }
        });
      },

      { threshold: [0.20] }
    );
    // create an array of all the components to be watched
    const components = [...document.querySelectorAll("[data-background]")];
    components.forEach((component) => {
      observer.observe(component);
    });
  }, []);

  return (
    <Page seo={{ title: "Starter Kit" }}>
      <Hero />
      <TechStack background="white"/>
      <TechStack background="grey" />
      <TechStack background="blue"/>
      <TechStack background="green"/>
      <TechStack background="grey"/>
      <TechStack background="white"/>
    </Page>
  );
};

export default Home;

【问题讨论】:

    标签: javascript html css reactjs next.js


    【解决方案1】:

    你可以在观察者挂载时动态添加元素,像这样

    <div ref={(r) => r && observer.observe(r)} />
    

    示例如下:https://codesandbox.io/s/sleepy-margulis-1f7hz7

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-10
      • 2014-07-24
      • 2015-03-20
      • 2011-10-23
      • 2023-03-26
      • 1970-01-01
      • 2015-08-11
      相关资源
      最近更新 更多