Blogger Information
Blog 46
fans 0
comment 0
visits 34391
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
选项卡实例演示
上草一方
Original
325 people have browsed it

实例演示选项卡

实例代码如下:

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>选项卡</title>
  8. <link rel="stylesheet" href="css/demo2.css">
  9. </head>
  10. <body>
  11. <div class="box">
  12. <!-- 1. 标签 -->
  13. <!-- 子元素上的点击事件会冒泡到父元素,利用这个特点,只需要给父元素添加点击事件就可以了 -->
  14. <ul class="menu" onclick="show()">
  15. <!-- 先给默认显示的标签和对应的内容添加 class="active"处于激活状态/可见 -->
  16. <!-- 使用自定义属性data-index使标签和与之对应的内容进行绑定 -->
  17. <li data-index="1" class="active">唐诗</li>
  18. <li data-index="2">宋词</li>
  19. <li data-index="3">论语</li>
  20. </ul>
  21. <!-- 2. 内容 -->
  22. <ul class="content active" data-index="1">
  23. <li>春眠不觉晓</li>
  24. <li>处处闻啼鸟</li>
  25. <li>夜来风雨声</li>
  26. <li>花落知多少</li>
  27. </ul>
  28. <ul class="content" data-index="2">
  29. <li>昨夜西风凋碧树</li>
  30. <li>独上高楼</li>
  31. <li>望尽天涯路</li>
  32. <li>欲寄彩笺兼尺素</li>
  33. <li>山长水阔知何处</li>
  34. </ul>
  35. <ul class="content" data-index="3">
  36. <li>学而时习之,不亦说乎</li>
  37. <li>有朋自远方来,不亦乐乎</li>
  38. <li>人不知而不愠,不亦君子乎</li>
  39. </ul>
  40. </div>
  41. <script>
  42. function show() {
  43. // 事件绑定者
  44. // console.log(event.currentTarget);
  45. // 事件主体
  46. // console.log(event.target);
  47. const ul = event.currentTarget;
  48. const li = event.target;
  49. // 1. 将原高亮的标签去掉active,并把当前的标签设置为active
  50. [...ul.children].forEach(li => li.classList.remove('active'));
  51. li.classList.add('active');
  52. // 2. 根据标签的data-index进行查询,获取与它对应的列表
  53. const content = document.querySelectorAll('.content');
  54. // document.querySelectorAll()返回的是NodeList对象,上面已定义了forEach,所以不用转真数组
  55. console.log(content);
  56. content.forEach(li => li.classList.remove('active'));
  57. console.log([...content].filter(ul => ul.dataset.index === li.dataset.index)[0]);
  58. // filter(ul => ul.dataset.index === li.dataset.index)[0]
  59. // 用find进行简化, find就是获取filter结果数组中的第一个
  60. [...content].find(ul => ul.dataset.index === li.dataset.index).classList.add('active');
  61. }
  62. </script>
  63. </body>
  64. </html>

效果图如下:

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post