到达屏幕顶部时将div固定到页面顶部

时间:2016-05-19 13:22:30

标签: jquery html css

当div到达页面顶部时,我正在尝试修复页面的侧边栏。我有以下代码(见下文)并且它正在工作..有点......它不会将类添加到正确的位置?有谁知道我做错了什么?

链接到页面:http://www.bluemoontesting.co.uk/bluemoon2016/people.html

CREATE TABLE tbl_Test_EOMONTH
(
    SampleDate DATETIME
)
GO

INSERT INTO tbl_Test_EOMONTH VALUES ('2015-12-20')
INSERT INTO tbl_Test_EOMONTH VALUES ('2015-11-08')
INSERT INTO tbl_Test_EOMONTH VALUES ('2015-10-16')
INSERT INTO tbl_Test_EOMONTH VALUES ('2015-09-26')
INSERT INTO tbl_Test_EOMONTH VALUES ('2016-01-31') 
GO

SELECT 
    DATEADD(DAY,8-DATEPART(WEEKDAY,DATEADD(DAY,0,EOMONTH([SampleDate])))
    ,EOMONTH([SampleDate])) AS FirstSunday_ofTheNextMonth
FROM tbl_Test_EOMONTH
GO

1 个答案:

答案 0 :(得分:1)

使用下面的jquery片段。这将使具有类'.wrapper'的元素跟随滚动,这意味着它将始终位于页面的顶部。在您的情况下,您可能需要调整偏移量。

var nav = $('.wrapper');
        var navHomeY = nav.offset().top;
        var isFixed = false;
        var $w = $(window);
        $w.scroll(function() {
          var scrollTop = $w.scrollTop();
          var shouldBeFixed = scrollTop > navHomeY;
          if (shouldBeFixed && !isFixed) {
            nav.css({
              position: 'fixed',
              top: 0,
              left: nav.offset().left,
              width: nav.width()
            });
            isFixed = true;
          }
          else if (!shouldBeFixed && isFixed)
          {
            nav.css({
              position: 'static'
            });
            isFixed = false;
          }
        });