javascript 如何找到一个元素在视口中可见的高度,并相应地将按钮放置在可见区域的中心?

lf5gs5x2  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(112)

我正试图把两个按钮在一个垂直的长div的中心。这应该呈现箭头按钮的基础上的div在视口中可见的数量。请帮助。
所以我写了这个use Effect with scroll event listeners,它应该生成div的top样式作为状态(这里是[arrowPosition,setArrowPosition])。但是我的visibleHeight值不正确。当我从top滚动时,它工作正常,然后回到它应该停留的地方。div内部有惰性加载,所以div可能会扩展,所以我认为有必要为此使用逻辑。

useEffect(() => {
    const handleScroll = () => {
        const { top, bottom, height } = epgRowsSpanRef.current.getBoundingClientRect(),
            windowHeight = window.innerHeight,
            topIntersection = Math.max(0, top),
            bottomIntersection = Math.max(0, windowHeight - bottom),
            visibleHeight = Math.min(height, Math.max(0, windowHeight - topIntersection - bottomIntersection)),
            visiblePercent = Math.round((visibleHeight / height) * 100);

        setArrowPosition(`${visiblePercent / 2}%`);
        console.log('show arrow', visibleHeight);
    };

    window.addEventListener('scroll', handleScroll);

    return () => {
        window.removeEventListener('scroll', handleScroll);
    };
}, [epgRowsSpanRef]);
kxe2p93d

kxe2p93d1#

你应该使用intersection observer来完成这个任务。

function buildThresholdList() {
  let thresholds = [];
  let numSteps = 20;

  for (let i = 1.0; i <= numSteps; i++) {
    let ratio = i / numSteps;
    thresholds.push(ratio);
  }

  thresholds.push(0);
  return thresholds;
}

function handleIntersect(entries, observer) {
  entries.forEach((entry) => {
    const ratio = entry.intersectionRatio;
    // calculate % visible from this
  });
}


function createObserver() {
  let observer;

  let options = {
    root: null,
    rootMargin: "0px",
    threshold: buildThresholdList(),
  };

  observer = new IntersectionObserver(handleIntersect, options);
  observer.observe(boxElement);
}

相关问题