[英]Stop fixed element scrolling at certain point
I have fixed sidebar which should scroll along with main content and stop at certain point when I scroll down.我有固定的侧边栏,它应该与主要内容一起滚动,并在我向下滚动时在某个点停止。 And vise versa when I scroll up.当我向上滚动时,反之亦然。
I wrote script which determines window height, scrollY position, position where sidebar should 'stop'.我编写了确定 window 高度、scrollY position、position 的脚本,其中侧边栏应该“停止”。 I stop sidebar by adding css 'bottom' property.我通过添加 css 'bottom' 属性来停止侧边栏。 But I have 2 problems with this approach:但是我对这种方法有两个问题:
Here's my code.这是我的代码。 HTML: HTML:
<div class="container">
<aside></aside>
<div class="content">
<div class="pagination"></div>
</div>
<footer></footer>
</div>
CSS: 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: 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', '');
}
});
Here's live demo on codepen这是codepen上的现场演示
Side bar is marked with orange background and block where it should stop is marked with blue.侧栏用橙色背景标记,应该停止的块用蓝色标记。 Than you for your help in advance.比你提前的帮助。
I solved my problem with solution described here我用这里描述的解决方案解决了我的问题
var windw = this;
let board = $('.pagination').offset().top;
let asideHeight = $('aside').outerHeight(true);
let coords = board - asideHeight;
console.log(coords)
$.fn.followTo = function ( pos ) {
var $this = this,
$window = $(windw);
$window.scroll(function(e){
if ($window.scrollTop() > pos) {
$this.css({
position: 'absolute',
top: pos
});
} else {
$this.css({
position: 'fixed',
top: 0
});
}
});
};
$('aside').followTo(coords);
And calculated coordinates as endpoint offset top - sidebar height.并将坐标计算为端点偏移顶部 - 侧边栏高度。 You can see solution in my codepen您可以在我的codepen中查看解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.