首页 > 解决方案 > 在特定点停止固定元素滚动

问题描述

我有固定的侧边栏,它应该与主要内容一起滚动,并在我向下滚动时在某个点停止。当我向上滚动时,反之亦然。

我编写了确定窗口高度、scrollY 位置、侧边栏应该“停止”的位置的脚本。我通过添加 css 'bottom' 属性来停止侧边栏。但是我对这种方法有两个问题:

  1. 当侧边栏接近应该停止的“分页”时,它突然跳下。当我向上滚动时,它突然跳了起来。
  2. 当我滚动页面时,侧边栏一直在移动

这是我的代码。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', '');
    }
});

这是codepen上的现场演示

侧栏用橙色背景标记,应该停止的块用蓝色标记。比你提前的帮助。

标签: javascriptjquerycss

解决方案


我用这里描述的解决方案解决了我的问题

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中查看解决方案


推荐阅读