根据滚动位置更改内容

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

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

enter image description here

我通过使用一些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',
    title: '',
  },
  {
    content: 'Gets a shit, rude requests from a person with 0 rating',
    title: '',
  },
  {
    content: 'Blocks them',
    title: '',
  },
  {
    content: 'Gets a nice request from a person who’s rated 5 stars',
    title: '',
  },
  {
    content: 'They agree on terms and accept the request',
    title: '',
  },
  {
    content: 'Time elapses',
    title: '',
  },
  {
    content: 'Thanks them for the time, gives them 5 stars',
    title: '',
  },
]

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

javascript reactjs typescript sticky
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.