上代碼 :
<!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; list-style: none; }
.tabs { font-size: 0; }
.tabs li { display: inline-block; padding: 10px; border: transparent solid 1px; border-bottom: 0; font-size: 12px; cursor: pointer; }
.tabs li.active { position: relative; border: 1px solid #cccccc; border-bottom: 0; font-weight: bold; }
.tabs li.active::before { position: absolute; bottom: -1px; left: 0; width: 100%; height: 1px; background: #ffffff; content: ""; }
.content { padding: 10px; border-top: #cccccc solid 1px; }
.content li { display: none; }
</style>
</head>
<script>
window.onload = function () {
let setTabs = function() {
class Tabs {
constructor (tab = 'tabs', val = 'content', inner1 = 'li', inner2 = 'li') {
this.tab = Array.from(document.getElementById(tab).getElementsByTagName(inner1))
this.val = Array.from(document.getElementById(val).getElementsByTagName(inner1))
}
run () {
this.tab.forEach((ele, index) => {
ele.onmouseover = () => {
this.tab.forEach((ele2, index2) => {
ele2.className = ''
this.setVal(index2, 'none')
})
this.setVal(index, 'block')
ele.className = 'active'
}
})
}
setVal (index, show) {
if (this.val[index]) this.val[index].style['display'] = show
}
init (index = 0) {
if (this.tab[index]) {
this.tab[index].className = 'active'
this.setVal(index, 'block')
}
}
}
return function (obj, index) {
let initList = ['tab', 'val', 'li1', 'li2']
let args = []
initList.forEach( ele => {
if (obj[ele]) args.push(obj[ele])
} )
let p1 = new Tabs(...args)
p1.run()
p1.init(index)
}
}()
// demo1
setTabs({},1)
// demo2
// obj 參數 順序隨意,key 不可變!
setTabs({
tab: 'tabs2', // id 導航 ul
li1: 'li', // 默認選擇 li (如果是li 可以不寫)
val: 'content2', // id 內容 ul
li2: 'li' // 默認選擇 li (如果是li 可以不寫)
}, 0) // 初始化選擇哪個標籤(下標) 不填默認 0
}
</script>
<body>
<!-- demo1 -->
<div class="set-tab">
<ul id="tabs" class="tabs">
<li>菜單1</li>
<li>菜單2</li>
<li>菜單3</li>
<li>菜單4</li>
</ul>
<ul id="content" class="content">
<li>內容1</li>
<li>內容2</li>
<li>內容3</li>
</ul>
</div>
<!-- demo2 -->
<div class="set-tab">
<ul id="tabs2" class="tabs">
<li>菜單1</li>
<li>sdfhsdskdjf</li>
<li>菜單3</li>
<li>菜單6</li>
</ul>
<ul id="content2" class="content">
<li>內容1</li>
<li>內容2</li>
<li>內容3</li>
</ul>
</div>
</body>
</html>