只有当向上滚动时,Jquery粘性导航 [英] Jquery sticky nav only when scrolling up

查看:90
本文介绍了只有当向上滚动时,Jquery粘性导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请检查此JPG以供参考:

Please check this JPG out for reference:

我有一个导航栏,显示在页面的顶部。我正在寻找的行为是:当你向上滚动,同一导航条淡入,并固定在屏幕的顶部。

I have a navigation bar that appears on the top of the page. The behaviour that I'm looking for is: When you scroll up, the same nav bar fades in and is fixed to the top of the screen.

我的代码使用这里工作,除了我不确定如何设置一个规则,停止导航从粘贴到屏幕的顶部,一旦你向回滚动到它的默认位置。目前,使用下面的代码,即使您向后滚动到页面顶部,导航仍保持固定在顶部。

The code I am using here works, except I am unsure how to set a rule that stops the nav from sticking to the top of the screen once you scroll back up to its default position. Currently, with the code below, the nav remains fixed to the top, even when you scroll back up to the top of the page.

function () {
var previousScroll = 0;

$(window).scroll(function(){
   var currentScroll = $(this).scrollTop();
   if (currentScroll > previousScroll){
        $('#header').fadeOut();
   } else {
        $('#header').fadeIn();
        $('#header').addClass('fixed');
   }
   previousScroll = currentScroll;
});

我的CSS是:

.fixed {
    position: fixed;
    top: 0;
}


推荐答案

附加变量记录 #header 元素的原始垂直偏移量。因为该值会在滚动事件触发时改变(因为固定位置会将偏移重置为0),所以我们将它声明为滚动事件之上一级:

You will have to declare an additional variable recording the original vertical offset of the #header element. As this value will change when the scroll event fires (as a fixed position will reset the offset to 0), we declare it one level above the scroll event:

$(document).ready(function() {
    var previousScroll = 0,
        headerOrgOffset = $('#header').offset().top;

    $(window).scroll(function() {
        var currentScroll = $(this).scrollTop();
        if(currentScroll > headerOrgOffset) {
            if (currentScroll > previousScroll) {
                $('#header').fadeOut();
            } else {
                $('#header').fadeIn();
                $('#header').addClass('fixed');
            }
        } else {
             $('#header').removeClass('fixed');   
        }
        previousScroll = currentScroll;
    });

});

查看概念证明在这里 - http://jsfiddle.net/teddyrised/6zGx6/

See proof of concept fiddle here - http://jsfiddle.net/teddyrised/6zGx6/

这篇关于只有当向上滚动时,Jquery粘性导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆