简体   繁体   English

页面顶部的透明导航

[英]Transparent navigation at top of page

I have the following code which adds/removes a class to my navigation div when the user scrolls. 我有以下代码,当用户滚动时,可以在导航div中添加/删除类。

 setInterval(function() {
  if (didScroll) {
  hasScrolled();
  didScroll = false;
}
}, 100);

function hasScrolled() {
    if ($(window).width() > 768) {
        var st = $(this).scrollTop();
        if (Math.abs(lastScrollTop - st) <= delta) {
            return;
        }
        if (st > lastScrollTop && lastScrollTop >= 0 && st > 0) {
            $('#anim-nav').removeClass('nav-down').addClass('nav-up');

        } else {
            $('#anim-nav').removeClass('nav-up').addClass('nav-down');

        }
    }
    lastScrollTop = st;
}

});

I want to add .trans-bg to #anim-nav when the user is close to the top of the screen. 我想在用户靠近屏幕顶部时将.trans-bg添加到#anim-nav中。 It has a background of white, but when it gets to the top o the screen I want it transparent as it goes over an image. 它具有白色背景,但是当它到达屏幕顶部或顶部时,我希望它在图像上方透明。 However when i added it to this function wasn't reliable. 但是,当我将其添加到此功能时并不可靠。 Sometimes it would stay transparent, or not turn transparent. 有时它会保持透明,或者不透明。

Not sure how to add something that constantly runs to make sure if the user is near/at the top it applies. 不确定如何添加可以连续运行的内容,以确保用户是否靠近/位于其顶部。

Maybe this can help? 也许这可以帮助?

 $(window).on('scroll', function () { if ($(window).scrollTop() > 10) { $('body').addClass('scrolled'); } else { $('body').removeClass('scrolled'); } }); 
 body { background: url("https://www.toptal.com/designers/subtlepatterns/patterns/christmas-black.png"); height: 3000px; } .scrolled .header { background-color: rgba(255, 255, 255, .8) } .header { background-color: #fff; height: 80px; position: fixed; left: 0; top: 0; right: 0; transition: .2s; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <header class="header"></header> 

Solution: Listen to scroll changes instead of checking for scrolls at a interval. 解决方案:聆听滚动更改,而不是间隔检查滚动。

Example of listening to scroll at top using javaScript: 使用javaScript监听顶部滚动的示例:

window.addEventListener('scroll', function(e) {
    if (document.body.scrollTop == 0) {
        alert("top");
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM