为了给浏览页面的用户提供更快捷、方便的导航,很多网站都提供了导航菜单栏随滚动条上下滚动的做法,以减少用户不必要的操作来提高网站用户粘度。并且很多的网站把导航条固定在网页的顶上,这样虽然好看,但是有的时候我们要在页面上呈现很多东西的时候,我们就会觉得固定在顶部的导航条是多余的。
这个时候,我们就可以通过本文的方法(使用headroom.js),使我们的网页在向下方滚动的时候,顶部的导航条会自动收起来(隐藏);网页在向上方滚动的时候,顶部的导航条再自动出现(显示)。这样就能给我们的页面更多的空间,视野更加开阔。相应效果请滑动本页观察本站导航栏的变化!
headroom.js的工作原理是:通过感应目标元素不同的3种状态(原始,下滚,上滚),为目标元素更改相应的class,通过相应的class的css样式的变化得到所要的效果。
下面龙笑天下就介绍实现方法:
第一种方式(推荐)
首先,在footer中加载下面的js:
- <!--智能显示隐藏导航栏http://www.ilxtx.com/auto-hide-navbar.html-->
- <scripttype="text/javascript"src="https://npmcdn.com/headroom.js@0.9.3/dist/headroom.min.js"></script>
- <script>
- (function(){
- newHeadroom(document.querySelector("#nav-scroll"),{//这里的nav-scroll改为你的导航栏的id或class
- offset:5,//在元素没有固定之前,垂直方向的偏移量(以px为单位)
- tolerance:5,//scrolltoleranceinpxbeforestatechanges
- classes:{
- initial:"animated",//当元素初始化后所设置的class
- pinned:"slideUp",//向上滚动时设置的class
- unpinned:"slideDown"//向下滚动时所设置的class
- }
- }).init();
- }());
- </script>
然后,加上样式就over了:
- .animated{position:fixed;top:0;left:0;right:0;transition:all.2sease-in-out;}
- .animated.slideDown{top:-100px;}
- .animated.slideUp{top:0;}
其中的class要与上面js中的相对应!
第二种方式
首先,依次引入下面4个js,注意顺序别错了,严格遵守!
- <scriptsrc="http://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
- <scripttype="text/javascript"src="https://npmcdn.com/headroom.js"></script>
- <scripttype="text/javascript"src="https://rawgithub.com/WickyNilliams/headroom.js/master/src/jQuery.headroom.js"></script>
- <scripttype="text/javascript">$(".navbar-fixed-top").headroom();</script>
其中,第一个jquery一般wordpress主题都带有了就可以不必再加载了;.navbar-fixed-top
为导航栏的class(也可以是id)。
然后,在引入css就ok了:
- .headroom{position:fixed;top:0;left:0;right:0;transition:all.2sease-in-out;}
- .headroom--unpinned{top:-100px;}
- .headroom--pinned{top:0;}
下面再给个具体的例子,用editplus或其它编辑器保存为html网页,双击即可看效果。修改自@大学IT网
- <!DOCTYPEhtml>
- <html>
- <head>
- <title>Bootstrap101Template</title>
- <metaname="viewport"content="width=device-width,initial-scale=1.0">
- <!--Bootstrap-->
- <linkrel="stylesheet"href="http://cdn.bootcss.com/twitter-bootstrap/3.0.3/css/bootstrap.min.css">
- <linkrel="stylesheet"href="I:/webpage/animate/animate.css">
- <!--HTML5ShimandRespond.jsIE8supportofHTML5elementsandmediaqueries-->
- <!--WARNING:Respond.jsdoesn'tworkifyouviewthepageviafile://-->
- <!--[ifltIE9]>
- <scriptsrc="http://cdn.bootcss.com/html5shiv/3.7.0/html5shiv.min.js"></script>
- <scriptsrc="http://cdn.bootcss.com/respond.js/1.3.0/respond.min.js"></script>
- <![endif]-->
- <styletype="text/css">
- .headroom{position:fixed;top:0;left:0;right:0;transition:all.2sease-in-out;}
- .headroom--unpinned{top:-100px;}
- .headroom--pinned{top:0;}
- </style>
- <styletype="text/css">
- .scrollspy-example{
- height:1200px;
- overflow:auto;
- position:relative;
- }
- </style>
- </head>
- <body>
- <!--页眉大屏显示-->
- <divclass="jumbotron">
- <divclass="container">
- <h1>Hello,world!</h1>
- <p>Thisisatemplateforasimplemarketingorinformationalwebsite.Itincludesalargecalloutcalledajumbotronandthreesupportingpiecesofcontent.Useitasastartingpointtocreatesomethingmoreunique.</p>
- <p><aclass="btnbtn-primarybtn-lg"role="button">Learnmore</a></p>
- </div>
- </div>
- <divclass="container">
- <!--导航栏-->
- <navclass="navbarnavbar-inversenavbar-fixed-top"role="navigation"id="example">
- <divclass="navbar-header">
- <aclass="navbar-brand"href="#">w3school</a>
- </div>
- <divclass="collapsenavbar-collapse"id="tem">
- <ulclass="navnavbar-nav">
- <liclass="active"><ahref="#php">PHP</a></li>
- <li><ahref="#js">JS</a></li>
- <liclass="dropdown">
- <ahref="#"class="dropdown-toggle"data-toggle="dropdown">database<bclass="caret"></b></a>
- <ulclass="dropdown-menu">
- <li><ahref="#mysql">MySQL</a></li>
- <li><ahref="#pgsql">PostgreSQL</a></li>
- <li><ahref="#mgdb">MogoDB</a></li>
- </ul>
- </li>
- </ul>
- </div>
- </nav>
- <!--主体内容-->
- <divdata-spy="scroll"data-target="#example"data-offset="0"class="scrollspy-example">
- <h4id="php">PHP</h4>
- <p>PHP,anacronymforHypertextPreprocessor,isawidely-usedopensourcegeneral-purposescriptinglanguage.ItisanHTMLembeddedscriptinglanguageandisespeciallysuitedforwebdevelopment.ThebasicsyntaxofPHPissimilartoC,Java,andPerl,andiseasytolearn.PHPisusedforcreatinginteractiveanddynamicwebpagesquickly,butyoucandomuchmorewithPHP.
- </p>
- <h4id="js">JS</h4>
- <p>
- JavaScriptisacross-platform,object-orientedscriptinglanguagedevelopedbyNetscape.JavaScriptwascreatedbyNetscapeprogrammerBrendanEich.ItwasfirstreleasedunderthenameofLiveScriptaspartofNetscapeNavigator2.0inSeptember1995.ItwasrenamedJavaScriptonDecember4,1995.AsJavaScriptworksontheclientside,Itismostlyusedforclient-sidewebdevelopment.
- </p>
- <h4id="mysql">MySQL</h4>
- <p>
- MySQLtutorialofw3cschoolisacomprhensivetutorialtolearnMySQL.Wehavehundredsofexamplescovered,oftenwithPHPcode.ThishelpsyoutolearnhowtocreatePHP-MySQLbasedwebapplications.
- </p>
- <h4id="pgsql">PostgreSQL</h4>
- <p>
- In1986theDefenseAdvancedResearchProjectsAgency(DARPA),theArmyResearchOffice(ARO),theNationalScienceFoundation(NSF),andESL,IncsponsoredBerkeleyPOSTGRESProjectwhichwasledbyMichaelStonebrakessr.In1987thefirstdemoversionoftheprojectisreleased.InJune1989,Version1wasreleasedtosomeexternalusers.Version2and3werereleasedin1990and1991.Version3hadsupportformultiplestoragemanagers,anqueryexecutorwasimproved,rulesystemwasrewritten.Afterthat,POSTGREShasbeenstartedtobeimplementedinvariousresearchanddevelopmentprojects.Forexample,inlate1992,POSTGRESbecametheprimarydatamanagerfortheSequoia2000scientificcomputingproject4.Usercommunityaroundtheprojectalsohasbeenstartedincreasing;by1993,itwasdoubled.
- </p>
- <h4id="mgdb">MongoDB</h4>
- <p>
- ThetermNoSQLwascoinedbyCarloStrozziintheyear1998.HeusedthistermtonamehisOpenSource,LightWeight,DataBasewhichdidnothaveanSQLinterface.Intheearly2009,whenlast.fmwantedtoorganizeaneventonopen-sourcedistributeddatabases,EricEvans,aRackspaceemployee,reusedthetermtoreferdatabaseswhicharenon-relational,distributed,anddoesnotconformtoatomicity,consistency,isolation,durability-fourobviousfeaturesoftraditionalrelationaldatabasesystems.
- </p>
- <p>
- AfterreadingthelargestthirdpartyonlineMySQLtutorialbyw3cschool,youwillbeabletoinstall,manageanddevelopPHP-MySQLwebapplicationsbyyourown.Wehaveacomprehensive,SQLTUTORIAL,whichwillhelpyoutounderstandhowtopreparequeriestofetchdataagainstvariousconditions.
- </p>
- </div>
- </div>
- <!--jQuery(necessaryforBootstrap'sJavaScriptplugins)-->
- <scriptsrc="http://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
- <!--Includeallcompiledplugins(below),orincludeindividualfilesasneeded-->
- <scriptsrc="http://cdn.bootcss.com/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
- <scripttype="text/javascript"src="https://npmcdn.com/headroom.js"></script>
- <scripttype="text/javascript"src="https://rawgithub.com/WickyNilliams/headroom.js/master/src/jQuery.headroom.js"></script>
- <scripttype="text/javascript">
- $(".navbar-fixed-top").headroom();
- </script>
- </body>
- </html>
参考资料:
- github中的源代码
- headroom.js官网
- headroom.js中文官网
- 简书headroom.js
以上就是JS代码如何实现导航菜单栏随滚动条向下滚动时隐藏向上滚动时显示。人无我有,人有我优,人优我奇。更多关于JS代码如何实现导航菜单栏随滚动条向下滚动时隐藏向上滚动时显示请关注haodaima.com其它相关文章!