滚动时隐藏导航栏的上部(平滑!)

时间:2020-04-17 14:55:27

标签: javascript css scroll navbar transitionend

您好,我自定义了具有两行的Bootstrap导航栏(上部只是徽标和社交链接,下部是导航链接)。滚动时,我试图隐藏上部,但是我找不到平滑的方法。我认为下面的代码是我找到的最好的解决方案,但是目前,transitionend上的事件监听器不起作用,并且永远不会添加“隐藏”类。

var scrollpos = window.scrollY;
var header = document.getElementById("header-up-section");

function add_class_on_scroll() {
    header.classList.add('visuallyhidden');
    header.addEventListener('transitionend', function(e) {
      header.classList.add('hidden');
    }, {
      capture: false,
      once: true,
      passive: false
    });
}

function remove_class_on_scroll() {
     header.classList.remove('hidden');
    setTimeout(function () {
      header.classList.remove('visuallyhidden');
    }, 20);
}

window.addEventListener('scroll', function(){

    scrollpos = window.scrollY;

    if(scrollpos > 20){
        add_class_on_scroll();
    }
    else {
        remove_class_on_scroll();
    }
    console.log(scrollpos);
});

*/and CSS :

#header-up-section.visuallyhidden {
  opacity: 0;
}

#header-up-section.hidden {
  display: none !important;
}

header-up-section变为不可见,但div不隐藏。有任何帮助的想法吗?

1 个答案:

答案 0 :(得分:0)

最后,不需要JS执行此操作。只需要2个引导程序导航栏,然后将引导程序类“粘顶”添加到第二个引导程序导航栏(这是两行导航栏的伪“向下部分”)。它完美地完成了工作;)