【问题标题】:Stop fixed element scrolling at certain point在特定点停止固定元素滚动
【发布时间】:2021-04-24 06:44:37
【问题描述】:

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

我编写了一个脚本来确定窗口高度、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', '');
    }
});

Here's live demo on codepen

侧栏用橙色背景标记,应该停止的块用蓝色标记。感谢您提前提供的帮助。

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    我用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);
    

    并将坐标计算为端点偏移顶部 - 侧边栏高度。你可以在我的codepen看到解决方案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多