![](/img/trans.png)
[英]Using a ref to find and scroll to the top position of child element in React
[英]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.