<!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>Document</title> <style> * { margin: 0; padding: 0; } ul, ol, li { list-style: none; } .container { width: 600px; height: 400px; border: 10px solid #333; margin: 30px auto; display: flex; flex-direction: column; } .container>ul { width: 100%; height: 40px; display: flex; } .container>ul>li { flex: 1; display: flex; justify-content: center; align-items: center; font-size: 30px; color: #fff; background-color: hotpink; } .container>ul>li.active { background-color: orange; } .container>ol { flex: 1; position: relative; } .container>ol>li { width: 100%; height: 100%; position: absolute; top: 0; left: 0; background-color: skyblue; color: #fff; font-size: 100px; display: flex; justify-content: center; align-items: center; display: none; } .container>ol>li.active { display: flex; } </style> </head> <body> <div class="container"> <ul> <li class="active">1</li> <li id="1">2</li> <li id="1">3</li> </ul> <ol> <li class="active">1</li> <li>2</li> <li>3</li> </ol> </div> <script> function Tab(lab){ // 获取页面元素 this.ulLiObj = lab.querySelectorAll(‘ul > li‘); this.olLiObj = lab.querySelectorAll(‘ol > li‘); } Tab.prototype.tab = function () { // 常量定义,用户无法修改 const _this = this; // ulli添加点击事件 this.ulLiObj.forEach((item, index) => { item.addEventListener(‘click‘, () => { // 去除其他liclass属性 _this.ulLiObj.forEach((ele, index) => { ele.removeAttribute(‘class‘); // 去除对应olli的class _this.olLiObj[index].removeAttribute(‘class‘); }) // 给自己添加class item.setAttribute(‘class‘, ‘active‘); // 给对应olli添加class _this.olLiObj[index].setAttribute(‘class‘, ‘active‘) }) }) } let divObj = document.querySelector(‘.container‘); let tab1 = new Tab(divObj); tab1.tab(); </script> </body> </html>
原文地址:https://www.cnblogs.com/CGWTQ/p/11675470.html
时间: 2024-10-10 23:48:32