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

J. Doe

我有一个可以垂直滚动的数字列表。我只希望它在滚动事件触发时获取放置在该列表中心的元素。

例如。在这个屏幕上我想得到 8

在此处输入图像描述

这里是沙盒

boop_the_snoot

这是一个使用 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>
  );
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章