我需要构建一个 onScroll 函数来检测屏幕上最大的 html 元素.基于数组中的 IDS



我需要构建一个onScroll函数来检测屏幕上最大的html元素。基于阵列中的 IDS。

如果我向下滚动页面并且第1 节比第 2 节占用的空间更多,我想将该值设置为状态。

import React, { useState } from 'react'
export default function Example() {
let [biggestSection, setBiggestSection] = useState("")
const handleOnScroll = (e) => {
let sectionIDS = ['section1', 'section2', 'section3', 'section4', 'section5', 'section6']

// When the user scrolls
// I need to know what element is taking up the most room 
// on the screen
// then set it to the biggestSection using the setBiggestSection hook
}
return (
<div onScroll={handleOnScroll}>
<section id={"section1"}>
{/* section content */}
</section>
<section id={"section2"}>
{/* section content */}
</section>
<section id={"section3"}>
{/* section content */}
</section>
<section id={"section4"}>
{/* section content */}
</section>
<section id={"section5"}>
{/* section content */}
</section>
<section id={"section6"}>
{/* section content */}
</section>
<section id={"section7"}>
{/* section content */}
</section>
<section id={"section8"}>
{/* section content */}
</section>
</div>
)
}

不知道为什么要在滚动上计算它,但你可以做这样的事情。

const handleOnScroll = (e) => {
let sectionIDS = ['section1', 'section2', 'section3', 'section4', 'section5', 'section6']
let largestSection;
let maxHeight = 0;
sectionIDS.forEach(sectionId => {
const section = document.getElementById(sectionId);
const sectionHeight = section.clientHeight;
if (sectionHeight > maxHeight) {
maxHeight = sectionHeight;
largestSection = sectionId;
}
});
setBiggestSection(largestSection);
}

我会考虑在这里使用"去抖动"。

最新更新