我知道如何在滚动时将工具栏保持在页面顶部,但是,我看到网站 http://seekingalpha.com/它有一个工具栏,只有当页面滚动通过标题部分(位于工具栏顶部)时,该工具栏才会保留在顶部。这个功能真的很酷,但我似乎无法弄清楚。
最佳答案
我将使用相同的页面作为示例:
Javascript
您将需要元素相对于窗口的位置;
var toolbar = document.getElementById('nav_container_wrap');
var bounds = toolbar.getBoundingClientRect();
bounds 对象包含这些数据:
bottom: 134 height: 32 left: -1 right: 1287 top: 102 width: 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');
}
});
关于jquery - 如何让工具栏保持在页面顶部只希望页面滚动通过一定的高度或元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25026828/