先來看看需要實現的需求:
這是某購物網站上經常看到的效果
我們把網頁的模型抽象出來,下面是我實現的效果圖:

源代碼僅供大家參考,具體如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
cursor: pointer;
}
.header {
height: 25px;
width: 100%;
height: 25px;
line-height: 25px;
padding-bottom: 1px;
}
/* 控制其顯示和隱藏 */
.show {
width: 100%;
height: 100%;
display: block !important;
}
/* 其子元素為隱藏狀態 */
.wrapper > div{
display: none;
}
.wrapper {
height: 600px;
width: 100%;
margin: 0 auto;
}
/* 添加下划線 */
.add2line {
color: #3385ff;
border-bottom: 1px solid #3385ff;
}
.header-tab {
display: flex;
justify-content: center;
}
.header-tab {
background-color: pink;
}
.box1 {
width: 100%;
height: 100%;
background-color: skyblue;
}
</style>
</head>
<body>
<nav class="header">
<ul class="header-tab" id="box">
<li class="add2line">更新內容</li>
<li>使用說明</li>
<li>福利中心</li>
<li>上架物品</li>
<li>我的寵物</li>
</ul>
</nav>
<main class="wrapper">
<div class="content show">
<div class="box1">頁面一</div>
</div>
<div class="content">
<div class="box1">頁面二</div>
</div>
<div class="content">
<div class="box1">頁面三</div>
</div>
<div class="content">
<div class="box1">頁面四</div>
</div>
<div class="content">
<div class="box1">頁面五</div>
</div>
</main>
</body>
</html>
<script>
window.onload = function () {
isShow()
function isShow () {
let liArr = document.querySelectorAll('#box > li')
let divArr = document.querySelectorAll('.wrapper .content')
for (let i = 0; i < liArr.length; i++) {
liArr[i].index = i;
// onmouseover事件會在鼠標指針移動到指定的對象上時觸發事件發生
// 也可以把其改成鼠標點擊事件 onclick
liArr[i].onmouseover = function () {
for (let j = 0; j < liArr.length; j++) {
liArr[j].className = ''
divArr[j].className = ''
}
divArr[this.index].className = 'show'
liArr[this.index].className = 'add2line'
}
}
}
}
</script>
