繁体   English   中英

粘性侧边栏仅在侧边栏底部位于窗口底部时才粘贴

[英]Sticky Sidebar that only sticks when sidebar bottom is at window bottom

我有2列的布局。 左列比边栏更长。 我只希望边栏在底部到达浏览器窗口底部时才粘住。 因此,用户可以在滚动右侧栏的同时继续向下滚动左列的内容。 我在这里看到了很多棘手的问题,但是这种特殊情况仍然让我感到困惑。 我在左列上也有一个粘贴的标题栏,我已经成功粘贴了。

这是我在jsfiddle中所做的演示

快速浏览一下我正在尝试的js。

    $(function(){
       var headlineBarPos = $('.headlineBar').offset().top; // returns number
       var sidebarHeight = $('.sticky-sidebar-wrap').height();
       var sidebarTop = $('.sticky-sidebar-wrap').offset().top;
       var windowHeight = $(window).height();

       var totalHeight = sidebarHeight + sidebarTop;

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

          var windowTop = $(window).scrollTop(); // returns number

          // fixing the headline bar    
          if (headlineBarPos < windowTop) {
              $('.headlineBar').addClass('sticky').css('top', '0');
          }
          else {
              $('.headlineBar').removeClass('sticky').removeAttr('style');
          }

        if(sidebarHeight < windowTop) {
            $('.sticky-sidebar-wrap').addClass('sticky').css('top', '0');
        } else {
           $('.sticky-sidebar-wrap').removeClass('sticky').removeAttr('style');
        }

        console.log(windowTop);

    });


    console.log(headlineBarPos);
    console.log(sidebarHeight);
    console.log(sidebarTop);

    });

我希望我做对了,当侧边栏的底部进入视图时,该坚持了吗?

我在侧边栏底部(在侧边栏内)创建了另一个div。 当看到它时,它会黏附。

http://jsfiddle.net/Z9RJW/10/

<div class="moduleController"></div> //inside the sidebar

和在js中

$(function () {


var headlineBarPos = $('.headlineBar').offset().top; // returns number
var moduleControllerPos = $('.moduleController').offset().top; // returns number    
var sidebarHeight = $('.sticky-sidebar-wrap').height();
var sidebarTop = $('.sticky-sidebar-wrap').offset().top;
var windowHeight = $(window).height();

var totalHeight = sidebarHeight + sidebarTop;

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

    var windowTop = $(window).scrollTop(); // returns number

    // fixing the headline bar    
    if (headlineBarPos < windowTop) {
        $('.headlineBar').addClass('sticky').css('top', '0');
    } else {
        $('.headlineBar').removeClass('sticky').removeAttr('style');
    }

    if (moduleControllerPos < windowTop + windowHeight) {
        $('.sticky-sidebar-wrap').addClass('sticky').css('top', '0');
    } else {
$('.sticky-sidebar-wrap').removeClass('sticky').removeAttr('style');        }






    console.log(windowTop);

});


console.log(headlineBarPos);
console.log(sidebarHeight);
console.log(sidebarTop);

});

希望对您有所帮助。

就像是:

if (sidebar.top + sidebar.height < window.scrolltop + window.height) {
    // set sticky
}

并设置粘性需要考虑到侧边栏可能高于视口,因此:

sidebar.top = sidebar.height - window.height // this will be a negative number

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM