Why is there such a demand? Have you found some websites abroad that when you scroll up, the navigation bar floats at the top position. If users want to see the content, they can click to reach it directly, which saves a lot of dragging time. Of course, it is easier to return to the top. But sometimes the button back to the top is often overlooked. Let’s take a look at the code and demonstration ( introducing jQuery 1.9 ).
To determine whether the mouse scrolls up or scrolls down, you can compare the coordinates of the user's last scroll with the coordinates of the next time. When the last time is less than the next time, that is, the user is scrolling down, otherwise, it means that the user is scrolling up. The scroll coordinate value can be used as the scrollTop of the window.
HTML code example
<div id="Jnav"> <ul> <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> <li><a href="#">front-end development</a></li> </ul></div>
JavaScript code examples
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); //Float, but it 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 the mouse to scroll up and display 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 example
.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 the example code of how to use js to implement floating navigation when the mouse scrolls up. If you are interested, please refer to it.