如何将工具栏保持在页面顶部只希望页面滚动通过一定的高度或元素?

时间:2014-07-30 00:03:57

标签: jquery html css jquery-ui

我知道如何在滚动时将工具栏保持在页面顶部,但是,我看到网站http://seekingalpha.com/只有当页面滚动通过标题部分时才会有工具栏工具栏顶部)。这个功能非常酷,但我似乎无法弄明白。

2 个答案:

答案 0 :(得分:0)

我将使用相同的页面作为示例:

<强>的Javascript

您将需要元素与窗口的相对位置;

var toolbar = document.getElementById('nav_container_wrap');
var bounds = toolbar.getBoundingClientRect();

bounds对象包含以下数据:

  

底部:134高度:32左:-1右:1287顶部:102宽度:1288

接下来,您将有一些事件监听器来监听滚动事件并检查此元素的最高值:

window.onscroll = function (event) {
  // called when the window is scrolled.
  var bounds = toolbar.getBoundingClientRect();
  if(bounds.top < 0) {
    //add class to the element here
    toolbar.className = toolbar.className + " top_nav_fixed";
  }
}

因此,当最高值低于零时 - 您必须将位置设置为固定(例如使用此类):

.top_nav_fixed {
   position: fixed !important;
   top: 0px !important;
   left: -2px !important;
   right: -1px !important;
   border-top: 0px !important;
   z-index: 49 !important;
}

<强>的jQuery

var toolbar = $('#nav_container_wrap');

$(window).scroll(function() { //when window is scrolled
    var bounds = toolbar.offset();
    if(bounds.top - $(window).scrollTop() < 0){
       $('#nav_container_wrap').addClass('top_nav_fixed');
    }
});

答案 1 :(得分:0)

以下是JSFiddle的实时示例。一般的想法是获取元素应附加到窗口的页面位置,当滚动位置超过该值时,将元素设置为具有固定位置。如果滚动位置低于计算值或硬编码值(element_position),则将其设置回默认值 - static。

jQuery代码

element_position = $("#nav").offset().top;

$(window).scroll(function(){
    scroll_position = $(window).scrollTop();

    if(scroll_position >= element_position)
    {
        $("#nav").css("position", "fixed");
    } else {
        $("#nav").css("position", "static");
    }
});