<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
.container{
width: 400px;
margin: 100px auto;
}
.nav{
list-style: none;
display:flex;
justify-content: space-between;
}
.nav li{
width: 60px;
padding: 4px 12px;
text-align: center;
border: solid 1px white;
background-color: orange;
cursor: pointer;
}
.nav li.on{
color: white;
font-weight: bold;
background-color: red;
}
.content{
padding: 10px;
border: solid 1px;
}
.content div{
width: 200px;
height: 200px;
margin: auto;
color: white;
font-size: 60px;
font-weight: bold;
text-align: center;
line-height: 200px;
border-radius: 50%;
background-color: purple;
display: none;
}
.content div.show{
display: block;
}
</style>
</head>
<body>
<div class="container">
<ul class="nav">
<li class="on">第一项</li>
<li>第二项</li>
<li>第三项</li>
<li>第四项</li>
<li>第五项</li>
</ul>
<div class="content">
<div class="show">1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
</div>
<script>
var lis = document.getElementsByTagName("li");
var content = document.getElementsByClassName("content")[0];
var items = content.getElementsByTagName("div");
for (var i = 0; i < lis.length; i++) {
lis[i].index = i;
lis[i].onclick = function () {
//先清除其它的样式
for (var j = 0; j < lis.length; j++) {
// lis[j].className = "";
lis[j].classList.remove("on");
//清除原来的内容
items[j].classList.remove("show");
}
//点击的这个导航 发生改变
// this.className = "on";
this.classList.add("on");
//显示对应的内容
items[this.index].classList.add("show");
}
}
</script>
</body>
</html>
js 对应思想
这篇博客展示了如何使用HTML、CSS和JavaScript创建一个导航菜单,当点击菜单项时,相应的内容会显示。CSS使用Flexbox布局来排列导航栏,JavaScript则用于实现内容的动态切换,突出显示被选中的导航项。示例代码中包含详细的样式和事件监听器设置。
摘要由CSDN通过智能技术生成