tab切换动画
效果图
代码
css部分
* {
margin: 0;
padding: 0;
}
#titles {
margin: 100px auto;
list-style: none;
width: 900px;
height: 50px;
overflow: hidden;
}
#titles>li {
float: left;
width: 300px;
line-height: 50px;
text-align: center;
background-color: blue;
}
#titles>li:first-child {
background-color: gold;
}
#contents {
width: 900px;
margin: 50px auto;
list-style: none;
}
#contents>li {
height: 400px;
text-align: center;
line-height: 400px;
}
#contents>li:first-child {
background-color: aqua;
}
#contents>li:nth-child(2) {
background-color: aquamarine;
display: none;
}
#contents>li:last-child {
background-color: blanchedalmond;
display: none;
}
html部分
<div>
<ul id="titles">
<li>标题一</li>
<li>标题二</li>
<li>标题三</li>
</ul>
<ul id="contents">
<li>内容一</li>
<li>内容二</li>
<li>内容三</li>
</ul>
</div>
js部分
var titles = document.getElementById('titles').getElementsByTagName('li');
var contents = document.getElementById('contents').getElementsByTagName('li');
// console.log(titles, contents);
// 遍历每个title
for (let i = 0; i < titles.length; i++) {
//给每个title绑定点击事件
titles[i].onclick = function () {
for (let j = 0; j < titles.length; j++) {
// console.log(this);
if (j == i) {
contents[j].style.display = 'block'
titles[i].style.backgroundColor = 'gold'
} else {
contents[j].style.display = 'none'
titles[j].style.backgroundColor = 'blue'
}
}
}
}