通过面向对象的方式实现tab选项卡效果
通过面向对象的方式实现tab选项卡效果
htm:
<div class="box" id="box"> <nav class="btnList"> <a href="javascript:;" class="on">第一个按钮</a><a href="javascript:;">第二个按钮</a><a href="javascript:;">第三个按钮</a> </nav> <ul class="conList"> <li style="display:block;">第一张选项卡</li> <li>第二张选项卡</li> <li>第三张选项卡</li> </ul> </div>
css:
*{ margin: 0; padding: 0; list-style: none; } html,body{ width: 100%; height: 100%; } .box{ width: 800px; height: 500px; /* outline: 1px dashed red; */ margin: 20px auto 20px; } .box .conList li{ width: 600px; height: 200px; line-height: 200px; font-size: 30px; color: #fff; text-align: center; /* 默认让所有的li 隐藏起来 */ display: none; } /* 让类名是on的li元素显示出来 */ .box .conList li.on{ display: block; } .box .conList li:nth-child(1){ background-color: #ff9900; } .box .conList li:nth-child(2){ background-color: #ff6699; } .box .conList li:nth-child(3){ background-color: purple; } .box .btnList a{ display: inline-block; color: #000; font-size: 23px; padding: 9px; text-decoration: none; } .box .btnList a.on{ color: #fff; font-weight: 800; } .box .btnList a:nth-of-type(1){ background-color: #ff9900; } .box .btnList a:nth-of-type(2){ background-color: #ff6699; } .box .btnList a:nth-of-type(3){ background-color: purple; }
js:
// 通过面向对象的方式创建 构造函数 function TabSwitch(parent){ // 定义属性----作用:获取内容区域的选项卡 this.ulList = parent.getElementsByTagName('ul')[0]; this.liList = this.ulList.getElementsByTagName('li'); // 定义属性----作用:获取控制按钮 this.btnList = parent.getElementsByTagName('nav')[0]; this.btns = this.btnList.getElementsByTagName('a'); // 定义属性----作用:获取按钮的长度 this.totalNum = this.btns.length; // 定义属性----作用:在事件中使用curIndex this.curIndex = 0; // 将构造函数体重的this存储起来----作用:在单击事件中,调用指向外层this。 var _this = this; // 对你点击的“控制按钮”进行遍历(逐一操作) for(var i=0; i<this.totalNum; i++){ //把 遍历过程中的i 存放在 每个按钮的index索引属性中 this.btns[i].index = i; // 单击 按钮 this.btns[i].onclick = function(){ // 将当前按钮身上的index索引上的值,存放在 构造函数的this.curIndex属性中 _this.curIndex = this.index; // console.log(_this.curIndex); _this.toSwitch(); } } } // 向 原型对象TabSwitch.prototype 中添加属性toSwitch TabSwitch.prototype.toSwitch = function(){ // 遍历 //(1) li,让当前li显示,其他li隐藏; //(2) a,让当前的a高亮显示 for(var i=0; i<this.totalNum; i++){ this.liList[i].style.display = 'none'; this.btns[i].style.color = '#000'; this.btns[i].style.fontWeight = 'normal'; } this.liList[this.curIndex].style.display = 'block'; this.btns[this.curIndex].style.color = '#fff'; this.btns[this.curIndex].style.fontWeight = '800'; } // console.log(TabSwitch.prototype); // 抓取对象 var box = document.getElementById('box'); // new 实例对象---是通过“new 实例的方式”构造出来的对象 // tab01实例对象 var tab01 = new TabSwitch(box); console.log(tab01.ulList); console.log(tab01.liList); console.log(tab01.btnList); console.log(tab01.btns); console.log(tab01.totalNum);
控制台数据输出,如下所示:
