1.tab部分可以根据不同标签来改变背景图片或背景色的不同。
示例如下:
话不多说,直接上代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.tab {
overflow: hidden;
border: 1px solid #ccc;
}
.tab button {
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
}
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
.tabcontentblock {
display: block;
}
.tablinksactive {
background: blue;
color: #ffffff;
}
.activeone {
background: red;
color: #ffffff;
}
.activetwo {
background: #333;
color: #ffffff;
}
.active {
background: blue;
color: #ffffff;
}
</style>
</head>
<body>
<div class="tab">
<button class="tablinks tablinksactive" οnclick="openTab(event, 'tab1',0)">选项卡1</button>
<button class="tablinks" οnclick="openTab(event, 'tab2',1)">选项卡2</button>
<button class="tablinks" οnclick="openTab(event, 'tab3',2)">选项卡3</button>
</div>
<div id="tab1" class="tabcontent tabcontentblock">
<p>这是选项卡1的内容。</p>
</div>
<div id="tab2" class="tabcontent">
<p>这是选项卡2的内容。</p>
</div>
<div id="tab3" class="tabcontent">
<p>这是选项卡3的内容。</p>
</div>
</body>
<script>
function openTab(evt, tabName, index) {
var i, tabcontent, tablinks;
console.log(tabName)
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
//判断当前点击的Tab元素下标,替换相对应的Class名
if (index == 0) {
tablinks[i].className = tablinks[i].className.replace("tabactive", "");
tablinks[i].className = tablinks[i].className.replace("active", "");
} else if (index == 1) {
tablinks[i].className = tablinks[i].className.replace("active", "");
tablinks[i].className = tablinks[i].className.replace("activeone", "");
} else if (index == 2) {
tablinks[i].className = tablinks[i].className.replace("activeone", "");
tablinks[i].className = tablinks[i].className.replace("activetwo", "");
}
}
document.getElementById(tabName).style.display = "block"; //展示相对应的元素
// 判断当前Tab下标,添加相对应的class名称
if (index == 0) {
evt.currentTarget.className += " active";
} else if (index == 1) {
evt.currentTarget.className += " activeone";
} else if (index == 2) {
evt.currentTarget.className += " activetwo";
}
}
</script>
</html>