最终实现效果图展示,通过点击tab栏,对内容进行切换。样式未进行美化。
具体思路见代码注释
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> * { padding: 0; margin: 0; box-sizing: border-box; } body { margin: 100px; } ul { list-style: none; display: flex; width: 400px; } ul li { width: 100px; height: 40px; text-align: center; line-height: 40px; border: 1px solid red; } .active { background: green; } .content-active { display: block; border: 1px solid green; } div { width: 400px; height: 300px; display: none; } </style> </head> <body> <ul> <li class="active">选项卡1</li> <li>选项卡2</li> <li>选项卡3</li> <li>选项卡4</li> </ul> <div class="content-active">内容一</div> <div>内容二</div> <div>内容三</div> <div>内容四</div> <script> // 简易tabs栏的切换 let ul = document.querySelector('ul'); let lis = document.querySelectorAll('li'); let divs = document.querySelectorAll('div'); // 为tab栏每一项都添加index属性,设置为索引 for (let i = 0; i < lis.length; i++) { lis[i].setAttribute('index', i); } // 事件委托到ul上,不用循环遍历绑定点击事件,利用e.target则可以找到点击的对应的li,然后再保存该li对应的属性index的值 ul.addEventListener('click', function (e) { let index = e.target.getAttribute('index'); // 利用了排他思想,先将所有的都移除该类 for (let i = 0; i < lis.length; i++) { lis[i].classList.remove('active'); divs[i].classList.remove('content-active'); } // 然后再对点击的类添加该类,就达到了效果 lis[index].classList.add('active'); divs[index].classList.add('content-active'); }); </script> </body> </html>