Jquery 如何保持工具栏在页面顶部,只希望页面滚动通过一定的高度或元素?
我知道滚动时如何保持工具栏在页面顶部,但是,我看到的网站只有当页面滚动通过标题部分(位于工具栏顶部)时,工具栏才保持在顶部。这项功能真的很酷,但我似乎无法理解 我将使用同一页作为示例: Javascript 您需要元素相对于窗口的相对位置Jquery 如何保持工具栏在页面顶部,只希望页面滚动通过一定的高度或元素?,jquery,html,css,jquery-ui,Jquery,Html,Css,Jquery Ui,我知道滚动时如何保持工具栏在页面顶部,但是,我看到的网站只有当页面滚动通过标题部分(位于工具栏顶部)时,工具栏才保持在顶部。这项功能真的很酷,但我似乎无法理解 我将使用同一页作为示例: Javascript 您需要元素相对于窗口的相对位置 var toolbar = document.getElementById('nav_container_wrap'); var bounds = toolbar.getBoundingClientRect(); bounds对象包含以下数据: 底部:134
var toolbar = document.getElementById('nav_container_wrap');
var bounds = toolbar.getBoundingClientRect();
bounds对象包含以下数据:
底部:134高度:32左:-1右:1287顶部:102宽度:1288
接下来,您将有一些事件侦听器来侦听scroll事件并检查此元素的最大值:
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";
}
}
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');
}
});
var-toolbar=$('nav#u-container_-wrap');
$(窗口).scroll(函数(){//当窗口被滚动时
var bounds=toolbar.offset();
if(bounds.top-$(window.scrollTop()<0){
$('nav#u container_wrap').addClass('top_nav_fixed');
}
});
下面是一个现场示例。一般的想法是获取元素应该附加到窗口的页面位置,当滚动位置超过该值时,将元素设置为具有固定位置。如果滚动位置低于计算值或硬编码值(元素位置),则将其设置回默认值-静态
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");
}
});
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");
}
});