【发布时间】:2021-12-21 21:30:17
【问题描述】:
我需要在滚动到达页脚之前固定这个黄色粘性框的位置。当页脚到达屏幕时,粘性框应与动态内容框一起滚动,反之亦然。我试过position: sticky 但没有运气。 javascript解决方案也可以。
我也尝试了下面的代码,但它不会顺利运行,因为position: relative 使sticky-content-box 直接跳到顶部,而不是滚动左侧内容。
const height = 900; // this would be calculated dynamic content box height
const backGroundAnimation = useCallback(() => {
if (window.scrollY > height) {
fixedBox!.current!.style.position = 'relative';
fixedBox!.current!.style.marginTop = `${height}px`;
} else {
fixedBox!.current!.style.position = 'fixed';
}
}, [height]);
useEffect(() => {
document.addEventListener('scroll', backGroundAnimation);
return () => document.removeEventListener('scroll', backGroundAnimation);
}, [backGroundAnimation]);
这是我的code sandbox 设置
请注意,在codesandbox 实现中,我没有在问题中包含我在此处添加的功能。
【问题讨论】:
-
我认为你想从页脚中分离黄色部分,并希望它只与红色部分保持相对。您可以设置
zIndex:-10,这样黄色的内容就会在页脚后面,不再隐藏页脚内容。 -
不附加到页脚,红色部分和黄色部分是相对元素
标签: html css reactjs typescript bootstrap-4