簡體   English   中英

當 CSS 使用 overflow: scroll 時,在 react 中找到 element 的 position

[英]Find position of element in react when CSS is using overflow: scroll

如果在 overflow: scroll 的父 div 上有 CSS,你如何在滾動時找到元素的 position? 我正在使用這樣的鈎子

const [scrollPosition, setScrollPosition] = useState(0);
  console.log(scrollPosition);

  const handleScroll = () => {
    const position = window.pageYOffset;
    setScrollPosition(position);
  };

  useEffect(() => {
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []); 

這在父 div 在 CSS 中沒有溢出屬性時有效,但是當我在它上面溢出時總是說 0。

試圖做到這一點,以便當 div 到達頁面頂部時,我想將其更改為幾乎像 header - 就像 spotify web 應用程序如何與他們的播放列表 header 一起工作。

有什么建議嗎?

window.pageYOffset顯示文檔主體的滾動條 position。 您應該尋找父元素的滾動條 position。

下面有一個鈎子,您可以使用它來獲取任何 HTML 元素的滾動條 position。 它為跟蹤元素的scrollTop屬性的滾動事件附加了一個事件處理程序。

import { useState, useRef, useLayoutEffect } from 'react';

export default function useScrollBarPosition() {
  const [top, setTop] = useState(0);
  const ref = useRef();

  useLayoutEffect(() => {
    function getTopPosition() {
      const topPosition = ref.current.scrollTop;
      setTop(topPosition);
    }
    ref.current.addEventListener('scroll', getTopPosition);
    getTopPosition();
    return () => ref.current.removeEventListener('scroll', getTopPosition);
  }, []);

  return [ref, top];
}

然后像這樣將它應用於您的元素:

import useScrollTop from './use-scroll-top';

function FooComponent() {
  const [ref, top] = useScrollTop();
  console.log(top);

  return (
    <parent ref={ref}>
      <child parentPosition={top} />
    </parent>
  );
}

嘗試使用 position: sticky for header https://developer.mozilla.org/en-US/docs/Web/CSS/position

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM