如何使节变粘,直到用户滚动特定的长度

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

我正在尝试复制类似于Postmates fleet website的内容,他们在节中使用position: sticky并更改该节中的元素,直到用户滚动浏览所有内容为止。

这是我的意思的示例:

Here's an example of it

到目前为止,我已经在要粘贴的部分设置了ref

        ref={(r) => this.ref = r}
     ...
/>

然后获得页面加载时容器的高度:

  componentDidMount() {
    if (this.ref) {
      this.setState({ targetY: this.ref.getBoundingClientRect().bottom },
      // tslint:disable-next-line:no-console
      () => console.log(this.state, 'state'))
    }
    window.addEventListener('scroll', this.handleScroll)
  }

[之后,我检测到页面的滚动并知道何时查看该部分:

  handleScroll(e) {
    const scrollY = window.scrollY + window.innerHeight;
    const { lockedIntoView, targetY } = this.state;
    // tslint:disable-next-line:no-console
    console.log(scrollY, "scrollY");
    if (scrollY >= targetY) {
      this.setState({ lockedIntoView: true }, () => {
        // tslint:disable-next-line:no-console
        console.log(`LockedIntoView: ${lockedIntoView}`);
      });
    } else {
      this.setState({ lockedIntoView: false }, () => {
        // tslint:disable-next-line:no-console
        console.log(`LockedIntoView: ${lockedIntoView}`);
      });
    }
  }

在将容器设置为粘性位置之前:

  <section
    ...
    style={{position: lockedIntoView ? "sticky" : ""}}
    ...
  </>

我想知道如何使其像postmates网站那样,该部分在屏幕上一直保持完整视图,直到滚动了内容为止(或者直到现在,直到用户滚动了指定的高度为止?)。 >

或者只是一个关于他们如何做的想法,以及我需要采取哪些步骤来复制它?

这是我的Codesandbox

我正在尝试复制类似于Postmates舰队网站的内容,他们在该网站上使用位置:粘贴在一个区域上并更改该区域内的元素,直到用户滚动浏览所有......>

javascript css reactjs sticky
1个回答
0
投票

要考虑的几件事:

1]当您将目标设置为position: fixed时,您会将其从dom流中删除,因此您需要通过向dom添加一些高度来进行补偿-下面的示例在body上执行此操作。

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