javascript - 在特定点停止固定元素滚动
问题描述
我有固定的侧边栏,它应该与主要内容一起滚动,并在我向下滚动时在某个点停止。当我向上滚动时,反之亦然。
我编写了确定窗口高度、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', '');
}
});
侧栏用橙色背景标记,应该停止的块用蓝色标记。比你提前的帮助。
解决方案
我用这里描述的解决方案解决了我的问题
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);
并将坐标计算为端点偏移顶部 - 侧边栏高度。您可以在我的codepen中查看解决方案
推荐阅读
- python - 在 Python 中读取图例的高度
- wix-extension - 从 WiX 3 迁移到 Wix 4 (4.0.0.5918) 现在会在 Candle.exe (CNDL0200) 中生成错误
- typescript - 创建 React 中间件以侦听所有操作的错误
- php - 无法通过引用传递参数 2 - Mysql Prepare 语句
- git - 如何在不查看 repo 的情况下直接从 github.com 获取 git 日志?
- config - spring cloud refresh 配置不会删除旧密钥
- sql - 如何从 SQL 中的日期时间获取格式为 dd.MM 的日期字符串
- javascript - 如何使用条件过滤 javascript 甘特图并处理空输入?
- ios - UITableView 在文本字段开始编辑时自动滚动
- r - 如何从循环数字中形成日期?