How to use js to realize floating navigation when the mouse scrolls up

  • 2021-07-04 17:42:07
  • OfStack

Why is there such a demand? Have you found some websites in foreign countries, when you scroll up, the navigation bar floats at the top position. If users want to see the content, they can click directly to reach it, which saves a lot of dragging time. Of course, it is easier to return to the top. But sometimes the button to go back to the top is often ignored. Let's take a look at the code and demo (introducing jQuery 1.9).

To judge whether the mouse scrolls upwards or downwards, we can compare the coordinates of the last scroll of the user with the coordinates of the next scroll. When the last scroll is less than the next scroll, the user is scrolling downwards; Otherwise, the user is scrolling upwards. The coordinate value of scrolling can take the scrollTop of the window.

HTML Code Sample


<div id="Jnav">
 <ul class="nav">
 <li><a href="http://caibaojian.com/">WEB Front-end development </a></li>
 <li><a href="#"> Front-end development blog </a></li>
 <li><a href="#"> Front-end development </a></li>
 <li><a href="#"> Front-end development </a></li>
 </ul>
</div>

JavaScript Code Sample


var $nav = $('#Jnav'), navTop = $nav.offset().top, navH = $nav.outerHeight(),winTop_1=0,winWidth=$(window).width(), holder=jQuery('<div>');
$(window).on('scroll',function(){
 var winTop_2 = $(window).scrollTop();
 holder.css('height',navH);
 // Begins to float, but does not display 
 if(winTop_2>navTop && winWidth>980){
 holder.show().insertBefore($nav);
 $nav.addClass('fixed-nav');
 }else{
 holder.hide();
 $nav.removeClass('fixed-nav');
 }
 // Judge that the mouse scrolls up and displays it 
 if(winTop_2>winTop_1 && winWidth>980){
 $nav.removeClass('fixed-nav-appear');
 }else if(winTop_2<winTop_1){
 $nav.addClass('fixed-nav-appear');
 }
 winTop_1 = $(window).scrollTop();
})

CSS Code Sample


.nav{width:980px; margin:0 auto;}
.nav li{display:inline-block; *display:inline; *zoom:1; margin:0 10px;}
.nav li a{display:block; padding:5px 10px;}
.fixed-nav{
 position: fixed;
 width:100%;
 top:-40px; 
 -webkit-transition: top .5s;
  -moz-transition: top .5s;
  -o-transition: top .5s;
  transition: top .5s;
  -webkit-box-shadow: 0 2px 2px rgba(0,0,0,.1);
  -moz-box-shadow: 0 2px 2px rgba(0,0,0,.1);
  box-shadow: 0 2px 2px rgba(0,0,0,.1);
}
.fixed-nav-appear{top:0;}

The above is how to use js mouse scroll up when floating navigation example code, interested can refer to the following.


Related articles: