<style>
* {
margin: 0;
padding: 0;
}
ul,
li {
list-style: none;
}
#tab_control {
width: 300px;
border: 1px solid #ccc;
margin: 200px auto;
}
#tab_list {
height: 60px;
}
#tab_list li {
float: left;
width: 100px;
height: 60px;
background-color: rgba(0, 0, 0, 0.2);
text-align: center;
line-height: 60px;
}
#tab_control>div {
width: 300px;
height: 350px;
}
#img_tab {
background-color: pink;
display: none;
}
#special_tab {
background-color: powderblue;
display: none;
}
#hot_tab {
background-color: floralwhite;
display: none;
}
/* 给选中的列表项和内容设置样式 */
#tab_list .active {
background-color: rgba(0, 0, 0, 0.3);
}
#tab_control .on {
display: block;
}
</style>
</head>
<body>
<!-- 选项卡 -->
<div id="tab_control">
<ul id="tab_list">
<li id="tab01" class="active">图片</li>
<li id="tab02">专栏</li>
<li id="tab03">热点</li>
</ul>
<div id="img_tab" class="on">
图片内容
</div>
<div id="special_tab">
专栏内容
</div>
<div id="hot_tab">
热点内容
</div>
</div>
<script>
window.onload = function() {
// 获取选项卡列表
let lis = document.querySelectorAll('#tab_list li')
// 获取选项卡内容
let tab_content = document.querySelectorAll('#tab_control>div')
console.log(tab_content)
// 遍历选项卡列表和选项卡内容
for (let i = 0; i < lis.length; i++) {
// 给选项卡列表绑定光标滑过事件
lis[i].addEventListener('mouseover', function() {
//遍历选项卡内容
for (let j = 0; j < tab_content.length; j++) {
// 清除lis和tab_content的className属性
lis[j].className = ''
tab_content[j].className = ''
}
// 让lis和tab_conten的索引保持一致,
lis[i].className = 'active'
tab_content[i].className = 'on'
})
}
}
</script>
</body>
js-实现选项卡功能
最新推荐文章于 2023-11-11 09:49:22 发布