如何在向下滚动时创建隐藏,并在向上滚动菜单中显示whitout jquery或其他依赖项

时间:2017-03-25 15:22:37

标签: javascript html css

我正在一个需要快速而轻盈的网站上工作。 我之前在其他网站上使用过这个脚本但是使用了jquery库。 对于这个特定的网站,我需要运行得非常快,因为大多数用户的移动互联网速度较低。 出于这个原因,我只想简单的javascript来完成这项任务。

我对javascript不太熟悉所以我需要一些帮助,这就是我要求的原因。

有人能帮帮我吗?

谢谢你, 约翰



// Hide Header on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

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

function hasScrolled() {
    var st = $(this).scrollTop();
    
    // Make sure they scroll more than delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;
    
    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('header').removeClass('nav-down').addClass('nav-up');
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('header').removeClass('nav-up').addClass('nav-down');
        }
    }
    
    lastScrollTop = st;
}
&#13;
body {
    padding-top: 40px;
}

header {
    background: #f5b335;
    height: 40px;
    position: fixed;
    top: 0;
    transition: top 0.2s ease-in-out;
    width: 100%;
}

.nav-up {
    top: -40px;
}

main {
   background:url(
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAPklEQVQYV2O8dOnSfwYg0NPTYwTRuAAj0QqxmYBNM1briFaIzRbi3UiRZ75uNgUHGbfvabgfsHqGaIXYPAMAD8wgC/DOrZ4AAAAASUVORK5CYII=
   ) repeat;
    height: 2000px;
}

footer { background: #ddd;}
* { color: transparent}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header class="nav-down">
    This is your menu.
</header>
<main>
    This is your body.
</main>
<footer>
    This is your footer.
</footer>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您可以使用:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
window.addEventListener(mousewheelevt, function(e){

var evt = window.event || e //equalize event object     
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to  originalEvent if possible               
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

  if(delta > 0) {
    document.getElementById('menu').style.display = "block";
  }
  else{
    if(window.pageYOffset > 250)
       document.getElementById('menu').style.display = "none";
  }   
});