javascript - jQuery 滚动到底部 addClass 不起作用

标签 javascript jquery html css

我正在尝试实现 navbar 在从页面底部滚动到顶部时固定。当我们从顶部滚动到底部时,位置必须是相对的。

I want to add the class when I scroll back to menu from bottom and remove it at the end reaching the menu again.

我试过使用负值的 scrollTop 但它对我不起作用。

提前致谢!

scrolldown-scrollup

$(window).scroll(function() {
    if ($(this).scrollTop() > 200) {
        $('nav').addClass("sticky");
    } else {
        $('nav').removeClass("sticky");
    }
});


$(window).scroll(function() {
    if ($(this).scrollTop() > -200) {
        $('nav').addClass("sticky");
    } else {
        $('nav').removeClass("sticky");
    }
});
* {
    box-sizing: border-box;
}

nav {
    height: 70px;
    background: #f00;
    position:relative;
}

nav.sticky {
    -webkit-transition: all 300ms ease-in 0s;
    transition: all 300ms ease-in 0s;
    left: 0;
    position: fixed;
    right: 0;
    top: 0;
    z-index: 1049;
}

section {
    height: 900px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<nav></nav>

<section></section>

最佳答案

var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
         $('nav').removeClass("sticky");

   } else {
      $('nav').addClass("sticky");
   }
   lastScrollTop = st;
});
* {
    box-sizing: border-box;
}

nav {
    height: 70px;
    background: #f00;
    position:relative;
}

nav.sticky {
    -webkit-transition: all 300ms ease-in 0s;
    transition: all 300ms ease-in 0s;
    left: 0;
    position: fixed;
    right: 0;
    top: 0;
    z-index: 1049;
}

section {
    height: 900px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav></nav>

<section></section>

您必须保存您的 ScrollTop 值并进行比较!

关于javascript - jQuery 滚动到底部 addClass 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56055270/

相关文章:

javascript - 我在 Angular JS 中选择的默认选择并删除两个单词之间的下划线

javascript - 如何在函数式 Vuejs 组件中发出事件

jquery - 我想使用固定 Bootstrap 导航栏的 stickyfloat.js

javascript - 使用 javascript 和 html、css 进行错误魔术缩放

javascript - 如何用更少的行编写以下代码

javascript - 在 PDF 中输入数字后自定义字符串的自定义按键

jquery - 将元素滚动到溢出的父容器的顶部

javascript - keyup 事件中的输入 val() 被延迟

html - 纵向模式下的 CSS 网格不需要的空白

html - 鼠标悬停按钮并同时触发 svg 圆圈