JS代码如何实现导航菜单栏随滚动条向下滚动时隐藏向上滚动时显示

日落沧海看夕阳,万丈霞光谱辉煌。轻叹美景难留住,只因月色要锋芒!你在桥上看风景,看风景的人在桥下看你。你只知道自己吃了韭菜盒子,却不知道别人在盒子里还加了鸡蛋。

为了给浏览页面的用户提供更快捷、方便的导航,很多网站都提供了导航菜单栏随滚动条上下滚动的做法,以减少用户不必要的操作来提高网站用户粘度。并且很多的网站把导航条固定在网页的顶上,这样虽然好看,但是有的时候我们要在页面上呈现很多东西的时候,我们就会觉得固定在顶部的导航条是多余的。

这个时候,我们就可以通过本文的方法(使用headroom.js),使我们的网页在向下方滚动的时候,顶部的导航条会自动收起来(隐藏);网页在向上方滚动的时候,顶部的导航条再自动出现(显示)。这样就能给我们的页面更多的空间,视野更加开阔。相应效果请滑动本页观察本站导航栏的变化!

headroom.js的工作原理是:通过感应目标元素不同的3种状态(原始,下滚,上滚),为目标元素更改相应的class,通过相应的class的css样式的变化得到所要的效果。

下面龙笑天下就介绍实现方法:

第一种方式(推荐)

首先,在footer中加载下面的js:

  1. <!--智能显示隐藏导航栏http://www.ilxtx.com/auto-hide-navbar.html-->
  2. <scripttype="text/javascript"src="https://npmcdn.com/headroom.js@0.9.3/dist/headroom.min.js"></script>
  3. <script>
  4. (function(){
  5. newHeadroom(document.querySelector("#nav-scroll"),{//这里的nav-scroll改为你的导航栏的id或class
  6. offset:5,//在元素没有固定之前,垂直方向的偏移量(以px为单位)
  7. tolerance:5,//scrolltoleranceinpxbeforestatechanges
  8. classes:{
  9. initial:"animated",//当元素初始化后所设置的class
  10. pinned:"slideUp",//向上滚动时设置的class
  11. unpinned:"slideDown"//向下滚动时所设置的class
  12. }
  13. }).init();
  14. }());
  15. </script>

然后,加上样式就over了:

  1. .animated{position:fixed;top:0;left:0;right:0;transition:all.2sease-in-out;}
  2. .animated.slideDown{top:-100px;}
  3. .animated.slideUp{top:0;}

其中的class要与上面js中的相对应!

第二种方式

首先,依次引入下面4个js,注意顺序别错了,严格遵守!

  1. <scriptsrc="http://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
  2. <scripttype="text/javascript"src="https://npmcdn.com/headroom.js"></script>
  3. <scripttype="text/javascript"src="https://rawgithub.com/WickyNilliams/headroom.js/master/src/jQuery.headroom.js"></script>
  4. <scripttype="text/javascript">$(".navbar-fixed-top").headroom();</script>

其中,第一个jquery一般wordpress主题都带有了就可以不必再加载了;.navbar-fixed-top为导航栏的class(也可以是id)。

然后,在引入css就ok了:

  1. .headroom{position:fixed;top:0;left:0;right:0;transition:all.2sease-in-out;}
  2. .headroom--unpinned{top:-100px;}
  3. .headroom--pinned{top:0;}

下面再给个具体的例子,用editplus或其它编辑器保存为html网页,双击即可看效果。修改自@大学IT网

  1. <!DOCTYPEhtml>
  2. <html>
  3. <head>
  4. <title>Bootstrap101Template</title>
  5. <metaname="viewport"content="width=device-width,initial-scale=1.0">
  6. <!--Bootstrap-->
  7. <linkrel="stylesheet"href="http://cdn.bootcss.com/twitter-bootstrap/3.0.3/css/bootstrap.min.css">
  8. <linkrel="stylesheet"href="I:/webpage/animate/animate.css">
  9. <!--HTML5ShimandRespond.jsIE8supportofHTML5elementsandmediaqueries-->
  10. <!--WARNING:Respond.jsdoesn'tworkifyouviewthepageviafile://-->
  11. <!--[ifltIE9]>
  12. <scriptsrc="http://cdn.bootcss.com/html5shiv/3.7.0/html5shiv.min.js"></script>
  13. <scriptsrc="http://cdn.bootcss.com/respond.js/1.3.0/respond.min.js"></script>
  14. <![endif]-->
  15. <styletype="text/css">
  16. .headroom{position:fixed;top:0;left:0;right:0;transition:all.2sease-in-out;}
  17. .headroom--unpinned{top:-100px;}
  18. .headroom--pinned{top:0;}
  19. </style>
  20. <styletype="text/css">
  21. .scrollspy-example{
  22. height:1200px;
  23. overflow:auto;
  24. position:relative;
  25. }
  26. </style>
  27. </head>
  28. <body>
  29. <!--页眉大屏显示-->
  30. <divclass="jumbotron">
  31. <divclass="container">
  32. <h1>Hello,world!</h1>
  33. <p>Thisisatemplateforasimplemarketingorinformationalwebsite.Itincludesalargecalloutcalledajumbotronandthreesupportingpiecesofcontent.Useitasastartingpointtocreatesomethingmoreunique.</p>
  34. <p><aclass="btnbtn-primarybtn-lg"role="button">Learnmore</a></p>
  35. </div>
  36. </div>
  37. <divclass="container">
  38. <!--导航栏-->
  39. <navclass="navbarnavbar-inversenavbar-fixed-top"role="navigation"id="example">
  40. <divclass="navbar-header">
  41. <aclass="navbar-brand"href="#">w3school</a>
  42. </div>
  43. <divclass="collapsenavbar-collapse"id="tem">
  44. <ulclass="navnavbar-nav">
  45. <liclass="active"><ahref="#php">PHP</a></li>
  46. <li><ahref="#js">JS</a></li>
  47. <liclass="dropdown">
  48. <ahref="#"class="dropdown-toggle"data-toggle="dropdown">database<bclass="caret"></b></a>
  49. <ulclass="dropdown-menu">
  50. <li><ahref="#mysql">MySQL</a></li>
  51. <li><ahref="#pgsql">PostgreSQL</a></li>
  52. <li><ahref="#mgdb">MogoDB</a></li>
  53. </ul>
  54. </li>
  55. </ul>
  56. </div>
  57. </nav>
  58. <!--主体内容-->
  59. <divdata-spy="scroll"data-target="#example"data-offset="0"class="scrollspy-example">
  60. <h4id="php">PHP</h4>
  61. <p>PHP,anacronymforHypertextPreprocessor,isawidely-usedopensourcegeneral-purposescriptinglanguage.ItisanHTMLembeddedscriptinglanguageandisespeciallysuitedforwebdevelopment.ThebasicsyntaxofPHPissimilartoC,Java,andPerl,andiseasytolearn.PHPisusedforcreatinginteractiveanddynamicwebpagesquickly,butyoucandomuchmorewithPHP.
  62. </p>
  63. <h4id="js">JS</h4>
  64. <p>
  65. JavaScriptisacross-platform,object-orientedscriptinglanguagedevelopedbyNetscape.JavaScriptwascreatedbyNetscapeprogrammerBrendanEich.ItwasfirstreleasedunderthenameofLiveScriptaspartofNetscapeNavigator2.0inSeptember1995.ItwasrenamedJavaScriptonDecember4,1995.AsJavaScriptworksontheclientside,Itismostlyusedforclient-sidewebdevelopment.
  66. </p>
  67. <h4id="mysql">MySQL</h4>
  68. <p>
  69. MySQLtutorialofw3cschoolisacomprhensivetutorialtolearnMySQL.Wehavehundredsofexamplescovered,oftenwithPHPcode.ThishelpsyoutolearnhowtocreatePHP-MySQLbasedwebapplications.
  70. </p>
  71. <h4id="pgsql">PostgreSQL</h4>
  72. <p>
  73. In1986theDefenseAdvancedResearchProjectsAgency(DARPA),theArmyResearchOffice(ARO),theNationalScienceFoundation(NSF),andESL,IncsponsoredBerkeleyPOSTGRESProjectwhichwasledbyMichaelStonebrakessr.In1987thefirstdemoversionoftheprojectisreleased.InJune1989,Version1wasreleasedtosomeexternalusers.Version2and3werereleasedin1990and1991.Version3hadsupportformultiplestoragemanagers,anqueryexecutorwasimproved,rulesystemwasrewritten.Afterthat,POSTGREShasbeenstartedtobeimplementedinvariousresearchanddevelopmentprojects.Forexample,inlate1992,POSTGRESbecametheprimarydatamanagerfortheSequoia2000scientificcomputingproject4.Usercommunityaroundtheprojectalsohasbeenstartedincreasing;by1993,itwasdoubled.
  74. </p>
  75. <h4id="mgdb">MongoDB</h4>
  76. <p>
  77. ThetermNoSQLwascoinedbyCarloStrozziintheyear1998.HeusedthistermtonamehisOpenSource,LightWeight,DataBasewhichdidnothaveanSQLinterface.Intheearly2009,whenlast.fmwantedtoorganizeaneventonopen-sourcedistributeddatabases,EricEvans,aRackspaceemployee,reusedthetermtoreferdatabaseswhicharenon-relational,distributed,anddoesnotconformtoatomicity,consistency,isolation,durability-fourobviousfeaturesoftraditionalrelationaldatabasesystems.
  78. </p>
  79. <p>
  80. AfterreadingthelargestthirdpartyonlineMySQLtutorialbyw3cschool,youwillbeabletoinstall,manageanddevelopPHP-MySQLwebapplicationsbyyourown.Wehaveacomprehensive,SQLTUTORIAL,whichwillhelpyoutounderstandhowtopreparequeriestofetchdataagainstvariousconditions.
  81. </p>
  82. </div>
  83. </div>
  84. <!--jQuery(necessaryforBootstrap'sJavaScriptplugins)-->
  85. <scriptsrc="http://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
  86. <!--Includeallcompiledplugins(below),orincludeindividualfilesasneeded-->
  87. <scriptsrc="http://cdn.bootcss.com/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
  88. <scripttype="text/javascript"src="https://npmcdn.com/headroom.js"></script>
  89. <scripttype="text/javascript"src="https://rawgithub.com/WickyNilliams/headroom.js/master/src/jQuery.headroom.js"></script>
  90. <scripttype="text/javascript">
  91. $(".navbar-fixed-top").headroom();
  92. </script>
  93. </body>
  94. </html>

参考资料:

  • github中的源代码
  • headroom.js官网
  • headroom.js中文官网
  • 简书headroom.js

以上就是JS代码如何实现导航菜单栏随滚动条向下滚动时隐藏向上滚动时显示。人无我有,人有我优,人优我奇。更多关于JS代码如何实现导航菜单栏随滚动条向下滚动时隐藏向上滚动时显示请关注haodaima.com其它相关文章!

您可能有感兴趣的文章
WordPress站点Gravatar头像前后台不显示的如何解决办法

WordPress做公司官网好吗?会不会显得档次很低?

WordPress主题需要支持https吗?WordPress站点如何如何实现https?

WordPress站点的页面/标签/分类URL地址如何添加.html?

WordPress站点更换了域名后数据库应该如何操作替换新旧域名?