簡體   English   中英

如何在 React 的滾動事件中獲取列表中心的元素?

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

我有一個可以垂直滾動的數字列表。 我希望它在滾動事件觸發時獲取放置在該列表中心的元素。

例如。 在這個屏幕上我想得到 8

在此處輸入圖像描述

這里是沙盒

這是一個使用 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