我正在尝试复制类似于Postmates fleet website的内容,他们在节中使用position: sticky
并更改该节中的元素,直到用户滚动浏览所有内容为止。
这是我的意思的示例:
到目前为止,我已经在要粘贴的部分设置了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舰队网站的内容,他们在该网站上使用位置:粘贴在一个区域上并更改该区域内的元素,直到用户滚动浏览所有......>
要考虑的几件事:
1]当您将目标设置为position: fixed
时,您会将其从dom流中删除,因此您需要通过向dom添加一些高度来进行补偿-下面的示例在body
上执行此操作。