且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

可以水平滚动的导航栏

更新时间:2022-08-22 17:36:37

有时候我们的水平导航栏的长度会超过屏幕宽度,那么如何增加水平滚动条呢?

使用场景:新闻页面的导航栏.

实现的效果如下:

火狐中:
可以水平滚动的导航栏
 chrome中:
可以水平滚动的导航栏
 代码如下:

Html代码  可以水平滚动的导航栏
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <meta charset="utf-8">  
  5. <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1.0 ,user-scalable=no">  
  6. <script src="http://www.ycf518518.com/static/js/jquery-1.11.1.js" type="text/javascript"></script>  
  7. <script >  
  8. window.onload=function()  
  9. {  
  10. var width = 0;  
  11.     $('nav div.container a').each(function () {  
  12.     width += (this.offsetWidth+10);//不包括超链接的margin  
  13.       
  14.   });  
  15.   //alert(width);  
  16.   $('#overflow div.container').css('width', width + "px");  
  17. }  
  18. </script>  
  19. <style>  
  20. #overflow {  
  21.         border: 1px solid #f00;  
  22.         overflow-x: scroll;  
  23.         overflow-y: hidden;  
  24.         width: 100%;   
  25.     }  
  26.     nav div a{  
  27.         margin-right: 10px;  
  28.         display:inline-block;  
  29.         float:left;  
  30.     }  
  31. </style>  
  32. </head>      
  33. <body>  
  34. <header>  
  35. <h1>新闻</h1>  
  36. </header>  
  37. <nav>  
  38. <div id="overflow" >  
  39. <div class="container">  
  40. <a href="index.asp">Home1</a>  
  41. <a href="html5_meter.asp">Previous2</a>  
  42. <a href="html5_noscript.asp">栏目3</a>  
  43. <a href="html5_noscript.asp">栏目4</a>  
  44. <a href="html5_noscript.asp">栏目5</a>  
  45. <a href="html5_noscript.asp">栏目6</a>  
  46. <a href="html5_noscript.asp">栏目7</a>  
  47. <a href="html5_noscript.asp">栏目8</a>  
  48. <a href="html5_noscript.asp">栏目9</a>  
  49. <a href="html5_noscript.asp">栏目10</a>  
  50. <a href="html5_noscript.asp">栏目11</a>  
  51. <a href="html5_noscript.asp">栏目12</a>  
  52. <a href="html5_noscript.asp">栏目13</a>  
  53. <a href="html5_noscript.asp">栏目14</a>  
  54. <a href="html5_noscript.asp">栏目15</a>  
  55.   
  56. </div>  
  57. </div>  
  58. </nav>  
  59. </body>  
  60. </html>  

 注意:

(1)超链接的样式一定要添加float:left

(2)overflow的宽度一定不能超过屏幕宽度,否则网页就会出现水平滚动条

这不是我们期望的效果:
可以水平滚动的导航栏
 

 

参考:http://hw1287789687.iteye.com/admin/blogs/2184331