简体   繁体   English

如何在 React 的滚动事件中获取列表中心的元素?

[英]How to get an element in center of list at scroll event in React?

I have a list of numbers which can scroll vertically.我有一个可以垂直滚动的数字列表。 All I want it to get element which placed in center of that list when scroll event fires.我希望它在滚动事件触发时获取放置在该列表中心的元素。

For ex.例如。 in this screen I want to get 8在这个屏幕上我想得到 8

在此处输入图像描述

Here is sandbox这里是沙盒

Here's a demo using the api - elementFromPoint这是一个使用 api 的演示- elementFromPoint


export default function App() {
  const refList = useRef();

  function onScroll({ target }) {
    // get the computed dimension of the list
    const { height, width, x, y } = target.getBoundingClientRect();

    // adding x and y as offsets. You may skip this
    const x1 = (width + x) / 2;
    const y1 = (height + y) / 2;

    console.log(document.elementFromPoint(x1, y1)); // prints the element from given point
  }

  return (
    <div className="App">
      <ul
        ref={refList}
        onScroll={onScroll}
      >
        {NUMBERS.map((i) => (
          <li key={i}>{i}</li>
        ))}
      </ul>
    </div>
  );
}

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

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