js菜单栏切换
先来看看需要实现的需求:
这是某购物网站上经常看到的效果
我们把网页的模型抽象出来,下面是我实现的效果图:

源代码仅供大家参考,具体如下:
<!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>

浙公网安备 33010602011771号