向 div 顶部添加项目时如何保持相同的滚动位置?

问题描述 投票:0回答:2

我希望当用户从 div 的底部滚动到顶部时将更多项目加载到该 div 到 div 的顶部,并且我想保持滚动位置(或者更确切地说,在添加更多项目之前确保顶部项目添加项目后仍然可见)

例如,如果我的项目 100 位于顶部,并且另外 100 个项目已加载到 div 中,那么我希望项目 100 仍然是滚动位置的焦点,当前当我将项目添加到 div 时,它会跳转到项目 200。 ..

我很想获得有关此问题的帮助,提前致谢:)

javascript html css reactjs
2个回答
2
投票

我发现这个答案很有用,我只是在 React 中创建了相同的逻辑 jquery - 在将项目添加到列表时保持窗口不更改滚动位置?


0
投票

您可以查看可滚动区域的

scrollHeight
属性。 当项目被添加到前面时,
scrollHeight
将会增加。 然后你可以计算
old_scrollHeight - scrollHeight
的差异。 最后,您从顶部滚动该元素的差异

// track the prev scrollHeight in state
const [scrollHeight, setScrollHeight] = useState(0);
    
useEffect(() => {
  const scrollableElement = scrollableRef.current;

  if (scrollableElement && scrollHeight != scrollableElement.scrollHeight) {
    const diff = scrollableElement.scrollHeight - scrollHeight;

    if (diff) {
      console.log({ diff });
      setTimeout(() => {
        scrollableElement.scrollTo({
          top: diff,
        });
      }, 0);
    }

    setScrollHeight(scrollableElement.scrollHeight);
  }

  console.log({ scrollHeight });
}, [scrollableRef, count, scrollHeight]);
© www.soinside.com 2019 - 2024. All rights reserved.