繁体   English   中英

如何在到达下一个 div 时更改导航栏颜色

[英]How to change the nav bar color when it reaches the next div

有没有办法让 header 在到达下一个 div 时改变颜色? 我试图让它在滚动到下一个 div“容器”时导航栏颜色发生变化

关联

就像@neaumusic 已经回答一样,添加滚动事件侦听器会有所帮助。

这是我写的一个工作代码: codesandbox

我喜欢做的是将事件侦听器分离到自定义钩子。

import { useEffect, useState, useRef, RefObject } from "react";

interface ITopBottom {
  top: number;
  bottom: number;
}

const useElementLocation = <T extends HTMLElement>(): [
  RefObject<T>,
  ITopBottom
] => {
  // ref object to return
  const ref = useRef<T>(null);

  // you can customize this to include width, height, etc.
  const [loc, setLoc] = useState<ITopBottom>({ top: 0, bottom: 0 });

  useEffect(() => {
    const listener = () => {


      const rect = ref.current?.getBoundingClientRect()
      if(rect){

        setLoc({
          top:rect.top,
          bottom: rect.bottom,
        })
      }
    };

    // add the listener as the component mounts
    window.addEventListener("scroll",listener)

    // guarantee the listener is executed at least once
    listener();

    // clean up
    return ()=>window.removeEventListener("scroll",listener)
  }, []);
  return [ref,loc]
};

export default useElementLocation;

此钩子返回要放置在 div 中的参考 object,以及您需要的相应 position。

现在知道了上下边界position,用逻辑语句判断header是否到达了目标div,根据结果改变颜色。

import React, {useState, useEffect} from 'react'
import useElementLocation from "./useElementLocation"

export default () => {
  const [headerRef, headerLoc] = useElementLocation<HTMLDivElement>();
  const [divRef, divLoc] = useElementLocation<HTMLDivElement>();

  const [headerColor, setHeaderColor] = useState("white"); // default color

  useEffect(()=>{
    const {bottom: headerBottom} = headerLoc;
    const {top,bottom} = divLoc;
    if(top<headerBottom && headerBottom<bottom){
      // header has reached the div
      setHeaderColor("black");
    } else {
      // header has left the div, either to the higher or lower
      setHeaderColor("white");
    }
  },[divLoc, headerLoc]) //dependencies

  return <div className="app">
    <div className="header" style={{backgroundColor: headerColor}} ref={headerRef}></header>
    <div className="div-to-watch" ref={divRef}></div>
  </div>
}

像这样的东西

container.addEventListener('scroll', e => {
  if (container.scrollTop > someChildElement.offsetTop) {
    changeColor(navbar);
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM