根据滚动位置更改内容

我正在尝试构建一个类似于the one seen hereShowcase组件,其中用户在滚动时浏览不同的内容:

根据滚动位置更改内容

我通过使用一些CSS来修复此部分:

.sticky {
  position: sticky;
}

.top-0 {
  top: 0;
}

应用于我的HTML:

  <section
    ref={(r) => this.ref = r}
    classname={`vh-500 bg-near-white z-max pv6-ns pv3 bg-near-white min-vh-100
    ...
    `}>
    <div classname='sticky top-0 vh-100'>

在我的HTML元素上使用ref,通过查看Showcase与该组件本身的顶部和底部之间的关系,得出scrollY组件粘滞的区域:

  componentDidmount() {
    if (this.ref) {
      this.setState(
        {
          firstThreshold: this.ref.getBoundingClientRect().top,secondThreshold: window.innerHeight * amount
        },// tslint:disable-next-line:no-console
        () => console.log(this.state,"state")
      );
    }
    window.addEventListener("scroll",this.handleScroll);
  }

然后在我的handleScroll()函数中,我们在滚动浏览Showcase组件时检测到了

// if we're scrolling through the Showcase component
if (scrollY >= firstThreshold && scrollY <= secondThreshold) {
...
}

现在这是我迷失的地方:

我通过将视口高度乘以我要在组件中显示的故事的章节数量来获得组件的高度:

const chapters = [
  {
    content: 'Signs up',title: '',},{
    content: 'Receives request',{
    content: 'Gets a shit,rude requests from a person with 0 rating',{
    content: 'Blocks them',{
    content: 'Gets a nice request from a person who’s rated 5 stars',{
    content: 'They agree on terms and accept the request',{
    content: 'Time elapses',{
    content: 'Thanks them for the time,gives them 5 stars',]

const amount = chapters.length

在我的handleScroll()函数中,我试图确定用户滚动显示哪一章,但是我不确定如何到达。这是我现在拥有的:

  for (let i = 0; i < amount; i++) {
    // tslint:disable-next-line:no-console
    console.log(i,"i");
    if (scrollY >= (firstThreshold + sectionThreshold) * i) {
      // tslint:disable-next-line:no-console
      console.log(sectionThreshold * i,"sectionThreshold * i");
      this.setState({ currentChapter: i },() => {
        // tslint:disable-next-line:no-console
        console.log(
          `scrolling inside section: ${this.state.currentChapter}`
        );
      });
    }
  }

我要实现的目标:

  • 在用户滚动浏览页面时显示每一章

我该怎么做?

Codesandbox

huazhua88225 回答:根据滚动位置更改内容

所以我设法弄清楚了,我想我以前只是想得太多。基本上在handleScroll(e)内部,您可以得到每个部分的高度:

首先,通过将chapterAmount除以componentHeight来获取章节的高度,然后将结果推入数组:

const chapterHeights = [];
for (let index = 0; index < chapters.length; index++) {
  const chapterHeight = componentHeight / chapterAmount;
  chapterHeights.push(chapterHeight * index);
}

然后循环遍历chapterHeights数组并将其与滚动位置进行比较,然后设置将在视图中呈现的titlecontent的状态。

for (let index = 0; index < chapterHeights.length; index++) {
  // console.log(chapterHeights[index],"chapterHeights[index]");
  const chapterLength = chapterHeights[index];

  if (scrollY >= chapterLength) {
    this.setState({
      title: chapters[index].title,content: chapters[index].content,})
  }
}

Codesandbox here

本文链接:https://www.f2er.com/3085114.html

大家都在问