ES5:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
text-align: center;
}
nav li {
display: inline;
width: 24%;
text-decoration: none;
padding: 15px;
}
li:hover {
background-color: lightblue;
}
section {
height: 300px;
}
.tab{
display: block;
}
section {
display: none;
}
</style>
</head>
<body>
<nav id="nav">
<ul>
<li >选卡1</li>
<li>选卡2</li>
<li>选卡3</li>
<li>选卡4</li>
</ul>
</nav>
<div id="container">
<section class="tab" style="background-color: tomato;">内容1</section>
<section style="background-color: cyan">内容2</section>
<section style="background-color: blueviolet">内容3</section>
<section style="background-color: gold">内容4</section>
</div>
<script>
window.onload = function() {
var li=document.getElementsByTagName('li');
var sec=document.getElementsByTagName('section');
console.log(li);
for (var i = 0; i < li.length; i++) {
li[i].index=i;
li[i].onmouseover=function () {
for (var i = 0; i < li.length; i++) {
li[i].className='';
sec[i].className='';
}
sec[this.index].className='tab';
}
}
};
</script>
</body>
</html>
ES6:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
text-align: center;
}
li {
display: inline;
width: 24%;
text-decoration: none;
padding: 15px;
}
li:hover {
background-color: lightblue;
}
section {
height: 300px;
}
.tab {
display: block;
}
section {
display: none;
}
</style>
</head>
<body>
<div class="box">
<ul>
<li id="li">选卡1</li>
<li>选卡2</li>
<li>选卡3</li>
<li>选卡4</li>
</ul>
<div id="container">
<section class="tab" style="background-color: tomato;">内容1</section>
<section style="background-color: cyan">内容2</section>
<section style="background-color: blueviolet">内容3</section>
<section style="background-color: gold">内容4</section>
</div>
</div>
<script>
var li = document.getElementById('li');
function Pander(sed) {
this.sed = document.querySelector(sed)
this.btn = this.sed.querySelectorAll('ul>li')
this.sec = this.sed.querySelectorAll('div>section')
this.change()
}
Pander.prototype.change = function() {
this.btn.forEach((item, index) => {
item.addEventListener('mouseover', () => {
this.btn.forEach((t, i) => {
t.className = ''
this.sec[i].className = ''
})
this.sec[index].className = 'tab'
})
})
}
let d1 = new Pander('.box')
</script>
</body>
</html>