0

我有一个 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);

    });
4

2 回答 2

1

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

我在侧边栏底部(侧边栏内)创建了另一个 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);

});

我希望它有所帮助。

于 2013-09-26T12:42:03.483 回答
0

就像是:

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

而设置sticky需要考虑到侧边栏可能高于视口,所以:

sidebar.top = sidebar.height - window.height // this will be a negative number
于 2013-09-26T12:34:02.467 回答