* index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>js + css 实现标签内容切换功能</title> <link type="text/css" rel="stylesheet" href="./css/style.css" /> </head> <body> <ul id="list-title"> <li class="list-item list-item-checked">1</li> <li class="list-item">2</li> <li class="list-item">3</li> </ul> <div id="content-box"> <div class="contents contents-checked">content_1</div> <div class="contents">content_2</div> <div class="contents">content_3</div> </div> <script type="text/javascript" src="./js/switchTabs.js"></script> <script> switchTabs(".list-item", ".contents", "list-item-checked", "contents-checked"); </script> </body> </html>
* css/style.css
#list-title { height: 60px; margin: 0; padding: 0; list-style-type: none; } .list-item { float: left; 100px; height: 50px; margin: 2px; line-height: 50px; font-size: 28px; text-align: center; border: 1px solid #ccc; cursor: pointer; } .list-item-checked { background-color: #70adff; color: #ffffff; } #content-box { position: relative; clear: both; margin: 0 2px; } .contents { position: absolute; left: 0; top: 0; 312px; height: 300px; font-size: 32px; line-height: 300px; text-align: center; border: 1px solid #ccc; z-index: 0; opacity: 0; visibility: hidden; -webkit-transition: all .5s; -moz-transition: all .5s; -ms-transition: all .5s; -o-transition: all .5s; transition: all .5s; } .contents-checked { z-index: 1; opacity: 1; visibility: visible; } #content-box > .contents:first-child { background-color: #c8ff40; } #content-box > .contents:nth-child(2) { background-color: #41ff6f; } #content-box > .contents:nth-child(3) { background-color: #ff82a0; }
* js/switchTabs.js
/* * tab:用于触发事件的标签的selector; * content:内容容器的类名; * ts:标签为选中状态时的样式; * cs:内容容器为选中状态时的样式; * 检查元素的类名列表中是否有指定的类名,如果有则移除,如果没有则添加; * */ function switchTabs(tab, content, ts, cs) { var tabs = document.querySelectorAll(tab), contents = document.querySelectorAll(content), last = 0; // 上一次选中元素的index tabs.forEach(function (tab, i) { (function (i) { tab.onclick = function () { tabs[last].classList.remove(ts); contents[last].classList.remove(cs); last = i; this.classList.add(ts); contents[i].classList.add(cs); } })(i); }); }