简体   繁体   English

如何检测反应js中div元素内的上下滚动?

[英]How to detect scroll up and down inside a div element in react js?

Currently, I have this custom hook to detect whether the user has scroll down/up the page entire page, but how can I implement it to detect scroll down and up inside a div element??目前,我有这个自定义钩子来检测用户是否向下/向上滚动页面整个页面,但是如何实现它来检测 div 元素内的向下和向上滚动?

By using a ref?通过使用参考? Any suggestion?有什么建议吗?


export const useScrollDirection = () => {
  const [scrollDirection, setScrollDirection] = useState(null);
  const [prevOffset, setPrevOffset] = useState(0);

  console.log("prevOffset", prevOffset);
  const toggleScrollDirection = () => {
    let scrollY = window.scrollY;
    console.log("scrollY", scrollY);
    if (scrollY === 0) {
      setScrollDirection(null);
    }
    if (scrollY > prevOffset) {
      setScrollDirection("down");
    } else if (scrollY < prevOffset) {
      setScrollDirection("up");
    }
    setPrevOffset(scrollY);
  };
  useEffect(() => {
    window.addEventListener("scroll", toggleScrollDirection);
    return () => {
      window.removeEventListener("scroll", toggleScrollDirection);
    };
  });
  return scrollDirection;
};

First, create a variable inside componentDidMount() and initialize with the current scroll position.首先,在componentDidMount()中创建一个变量并使用当前滚动 position 进行初始化。 Then attach the handleScroll() to a target element.然后将handleScroll()附加到目标元素。 I am using this hope this will help you too.我正在使用这个希望这对你也有帮助。

componentDidMount() {
    this.prev = window.scrollY;
}
handleScroll = (e) => {
    //console.log("scrolling!", e.target.scrollTop);

    const window = e.target;

    if (this.prev > window.scrollTop) {
      console.log("scrolling up");
    } else if (this.prev < window.scrollTop) {
      console.log("scrolling down");
    }
    this.prev = window.scrollTop;
};

Then attach handleScroll() to the target element.然后将handleScroll()附加到目标元素。

<div onScroll={this.handleScroll}>
</div>

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

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