当前位置: 代码迷 >> JavaScript >> 粘性侧边栏是否短于窗口高度,是否果冻?
  详细解决方案

粘性侧边栏是否短于窗口高度,是否果冻?

热度:29   发布时间:2023-06-05 11:47:46.0

我有一个粘性的侧边栏,当您在侧边栏底部查看时,滚动时固定。

如果侧边栏超出了此页面的长度,则在滚动时一切正常,这正是您所期望的。

但是,如果侧边栏比此的窗口高度短,则在滚动时它似乎在跳动,而我无法解决如何使其停止跳动并保持平滑。 换句话说,只有在侧边栏的底部碰到窗口的底部时,才应该固定它。

我对jQuery不太满意,因此不胜感激。

$(function () {  
  if ($('.leftsidebar').offset()!=null) {

    var top = $('.leftsidebar').offset().top - parseFloat($('.leftsidebar').css('margin-top').replace(/auto/, 0));
    var height = $('.leftsidebar').height();
    var winHeight = $(window).height(); 
    var footerTop = $('#footer').offset().top - parseFloat($('#footer').css('margin-top').replace(/auto/, 0));
    var gap = 7;

    $(window).scroll(function (event) {

      // what the y position of the scroll is
      var y = $(this).scrollTop();

      // whether that's below the form
      if (y+winHeight >= top+ height+gap && y+winHeight<=footerTop) {

          // if so, ad the fixed class
          $('.leftsidebar').addClass('leftsidebarfixed').css('top', winHeight-height-gap +'px');
      } 

      else if (y+winHeight>footerTop) {
          // if so, ad the fixed class
          $('.leftsidebar').addClass('leftsidebarfixed').css('top', footerTop-height-y-gap + 'px');
      } 
      else {
          // otherwise remove it
           $('.leftsidebar').removeClass('leftsidebarfixed').css('top', '0px');
      }
    });
  }  
});

是否可以合并两个实例? 因此,如果它的相对较短的停留时间相对于侧边栏到达底部为止,那么如果侧边较长则像现在一样作用吗?

该代码按预期工作。 这实际上是一个概念问题。

想象一下它将如何工作。 您描述它工作的方式似乎恰好是您演示中的工作方式。 如果边栏长于页面,则滚动页面会在添加leftsidebarfixed之前到达边栏底部。 如果边栏较短,那是不可能的。

您可能需要考虑将侧边栏固定在顶部,而不是固定在底部(大多数带有侧边栏的网站确实如此)或具有较高的标题,以便侧边栏从底部开始。

  相关解决方案