<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
div {
width: 400px;
height: 400px;
margin: 100px auto;
background: pink;
}
ul {
width: 400px;
height: 40px;
background: pink;
display: flex;
}
ul>li {
width: 100%;
height: 40px;
text-align: center;
line-height: 40px;
color: white;
background: green;
border-right: 1px solid white;
}
ol {
width: 400px;
height: 360px;
background: yellow;
}
ol>li {
color: black;
display: none;
}
ul>.active {
background: pink;
color: red;
}
</style>
</head>
<body>
<div class="box">
<ul>
<li>标题1</li>
<li>标题2</li>
<li>标题3</li>
<li>标题4</li>
</ul>
<ol>
<li>内容1</li>
<li>内容2</li>
<li>内容3</li>
<li>内容4</li>
</ol>
</div>
</body>
<script>
var ul = document.getElementsByTagName("ul")[0];
var ol = document.getElementsByTagName("ol")[0];
var uLi = ul.getElementsByTagName("li");
var oLi = ol.getElementsByTagName("li");
for (var i = 0; i < uLi.length; i++) {
uLi[i].index = i;
uLi[i].onclick = function() {
for (var i = 0; i < uLi.length; i++) {
uLi[i].className = '';
oLi[i].style.display = 'none';
}
this.className = 'active';
oLi[this.index].style.display = 'block';
};
}
</script>
</html>
实现思路
首先在html中写上标题以及内容样式自行设置
内容先给他设置display: none;
对其隐藏
当点击标题时获取当前标题的下表,对其内容的下表设置display = 'block'
对其显示
需要注意的是标题还有内容的下表要对应上
比如要默认显示第三个那么在html中
<body>
<div class="box">
<ul>
<li>标题1</li>
<li>标题2</li>
<li class="active">标题3</li>
<li>标题4</li>
</ul>
<ol>
<li>内容1</li>
<li>内容2</li>
<li style="display: block;">内容3</li>
<li>内容4</li>
</ol>
</div>
</body>
如果默认显示第一个则在标题一以及内容一上添加class="active"
以及style="display: block;"
最终效果