【发布时间】:2021-04-24 06:44:37
【问题描述】:
我有固定的侧边栏,它应该与主要内容一起滚动,并在我向下滚动时在某个点停止。当我向上滚动时,反之亦然。
我编写了一个脚本来确定窗口高度、scrollY 位置、侧边栏应该“停止”的位置。我通过添加 css 'bottom' 属性来停止侧边栏。但我对这种方法有两个问题:
- 当侧边栏接近应该停止的“分页”时,它突然跳下。当我向上滚动时,它突然跳了起来。
- 当我滚动页面时,侧边栏一直在移动
这是我的代码。 HTML:
<div class="container">
<aside></aside>
<div class="content">
<div class="pagination"></div>
</div>
<footer></footer>
</div>
CSS:
aside {
display: flex;
position: fixed;
background-color: #fff;
border-radius: 4px;
transition: 0s;
transition: margin .2s, bottom .05s;
background: orange;
height: 350px;
width: 200px;
}
.content {
display: flex;
align-items: flex-end;
height: 1000px;
width: 100%;
background: green;
}
.pagination {
height: 100px;
width: 100%;
background: blue;
}
footer {
height: 500px;
width: 100%;
background: red;
}
JS:
let board = $('.pagination')[0].offsetTop;
let filterPanel = $('aside');
if (board <= window.innerHeight) {
filterPanel.css('position', 'static');
filterPanel.css('padding-right', '0');
}
$(document).on('scroll', function () {
let filterPanelBottom = filterPanel.offset().top + filterPanel.outerHeight(true);
let bottomDiff = board - filterPanelBottom;
if(filterPanel.css('position') != 'static') {
if (window.scrollY + window.innerHeight - (bottomDiff*2.6) >= board)
filterPanel.css('bottom', window.scrollY + window.innerHeight - board);
else
filterPanel.css('bottom', '');
}
});
侧栏用橙色背景标记,应该停止的块用蓝色标记。感谢您提前提供的帮助。
【问题讨论】:
标签: javascript jquery css