运行效果参考:

1.gif

代码部分:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>选项卡</title>
  6. <style type="text/css">
  7. *{
  8. padding: 0;
  9. margin: 0;
  10. }
  11. body{
  12. height: 100%;
  13. }
  14. .wrapper{
  15. width: 600px;
  16. border: 1px solid red;
  17. margin: 30px auto;
  18. }
  19. ul{
  20. list-style: none;
  21. overflow: hidden; /*注意要清除浮动*/
  22. }
  23. ul a{
  24. display: block;
  25. text-decoration: none;
  26. width:200px;
  27. height: 50px;
  28. text-align: center;
  29. line-height: 50px;
  30. color: black;
  31. }
  32. ul li{
  33. float: left;
  34. background-color: rgba(0,0,0,.3);
  35. }
  36. p{
  37. width: 600px;
  38. height: 150px;
  39. line-height: 150px;
  40. text-align: center;
  41. display: none;
  42. }
  43. ul li.active{
  44. background-color: #ffffff;
  45. }
  46. p.active{
  47. display: block;
  48. }
  49. </style>
  50. </head>
  51. <body>
  52. <div class="wrapper">
  53. <ul>
  54. <li class="active"><a href="#">首页</a></li>
  55. <li><a href="#">新闻</a></li>
  56. <li><a href="#">热卖</a></li>
  57. </ul>
  58. <p id="home" class="active">首页内容</p>
  59. <p id="news">新闻内容</p>
  60. <p id="hotPurchase">热卖内容</p>
  61. </div>
  62. </body>
  63. <script type="text/javascript">
  64. var lis = document.getElementsByTagName('li');
  65. var ps = document.getElementsByTagName('p');
  66. for(var i = 0;i < lis.length; i++){
  67. lis[i].index = i; //这个用来记录每个标签的遍历位置,不用this,这里this指代的应该是window
  68. lis[i].onclick = function () {
  69. /*
  70. 思路
  71. * 1.清除所有标签上的active
  72. * 2.将单击的li和p标签都添加active属性
  73. */
  74. //清空class
  75. for(var j = 0;j < lis.length; j++){
  76. lis[j].className = '';
  77. ps[j].className = '';
  78. }
  79. //注意:这有个坑,不能跳!!!不能用遍历的i,要用this下的属性index
  80. this.className = 'active';
  81. ps[this.index].className = 'active';
  82. }
  83. }
  84. </script>
  85. </html>