龙空技术网

原生JS实现TAB选项卡切换效果

牙买加花裤衩 252

前言:

眼前小伙伴们对“tab效果js”大致比较重视,我们都需要了解一些“tab效果js”的相关文章。那么小编也在网上汇集了一些对于“tab效果js””的相关知识,希望你们能喜欢,大家一起来了解一下吧!

插件化写法:

HTML:

<div class="wrape">

<div class="tab clearfix">

<div class="t-item">tab1</div>

<div class="t-item">tab2</div>

<div class="t-item cur">tab3</div>

<div class="t-item">tab4</div>

<div class="t-item">tab5</div>

</div>

<div class="page">

<div class="p-item cur">页面1</div>

<div class="p-item">页面2</div>

<div class="p-item">页面3</div>

<div class="p-item">页面4</div>

<div class="p-item">页面5</div>

</div>

</div>

css:

.wrap{height:500px;width:80%;margin:50px auto;box-shadow:5px #ccc;}.fl{float:left;}.clearfix:after{content:'';display:table;clear:both;}.tab .t-item{float:left;width:20%;text-align:center;border:1px solid #ccc;box-sizing:border-box;padding:10px 0;cursor:pointer;}.tab .t-item.cur{color:red;background:#efefef;}.page{position:relative;height:450px;}.page .p-item{display:none;line-height:100px;height:100px;text-align:center;position:absolute;top:0px;left:0;height:100%;width:100%;}.page .p-item.cur{display:block;}

效果预览:

js:

;(() => { var Tab = function () { this.tab = document.getElementsByClassName('tab')[0] this.tabs = document.getElementsByClassName('t-item') this.pages = document.getElementsByClassName('p-item') } Tab.prototype = { init: function () { this.bindEvent() }, bindEvent: function () { this.tab.addEventListener('click', this.tabClick.bind(this), false) }, tabClick: function (e) { var e = e || window.event, tar = e.target || e.src.Element, className = tar.className, oTabs = this.tabs, oPages = this.pages, len = oTabs.length, thisIndex = Array.prototype.indexOf.bind(oTabs, tar)(), tItem, pItem if (className === 't-item') { for (var i = 0; i < len; i++) { tItem = oTabs[i] pItem = oPages[i] tItem.className = 't-item' pItem.className = 'p-item' } oTabs[thisIndex].className += ' cur' oPages[thisIndex].className += ' cur' } } } return new Tab().init()})()

标签: #tab效果js