项目要求
使用JS实现一个选项卡效果
代码演示
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>选项卡</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,body{
height: 100%;
width: 100%;
}
html{
font-size: 10px;
}
/*页面*/
.tab{
width: 400px;
height: 300px;
border: solid 1px #000;
}
.title{
width: 100%;
height: 50px;
background-color: blanchedalmond;
border-bottom: solid 2px red;
/*弹性布局*/
display: flex;
justify-content: space-between;
align-items: center;
}
.t{
flex: 1;
height: 50px;
background-color: oldlace;
font-size: 18px;
text-align: center;
line-height: 50px;
cursor: pointer;
}
/*连着写是子标签*/
.t.active,.t:hover{
background-color: orange;
color: white;
}
/*内容*/
.content{
width: 100%;
height: 250px;
background-color: aquamarine;
position: relative;
}
.tc{
width: 100%;
height: 100%;
font-size: 18px;
text-align: center;
color: aliceblue;
position: absolute;
display: none;
}
.tc:nth-of-type(1){
background-color: blue;
}
.tc:nth-of-type(2){
background-color: red;
}
.tc:nth-of-type(3){
background-color: green;
}
.tc.active{
display: block;
}
</style>
</head>
<body>
<div class="tab">
<!--标题:.table>.t{标题$}*3-->
<div class="title">
<div class="t active">标题1</div>
<div class="t">标题2</div>
<div class="t">标题3</div>
</div>
<!--内容:.content>.tc{内容$}*3-->
<div class="content">
<div class="tc active">内容1</div>
<div class="tc">内容2</div>
<div class="tc">内容3</div>
</div>
</div>
<script>
let ts = document.getElementsByClassName("t")
console.log(ts)
//循环
for(let i = 0;i<ts.length;i++){
ts[i].onmouseenter = function(){
//console.log("鼠标进入了编号为",i,"的标题")
for(let j = 0;j<ts.length;j++){
ts[j].classList = "t"
}
//高亮标题
ts[i].classList = "t active"
//全灭内容
let tcs = document.getElementsByClassName("tc")
for(let x = 0;x<tcs.length;x++){
tcs[x].classList = "tc"
}
//高亮内容
tcs[i].classList = "tc active"
}
}
</script>
</body>
</html>
效果演示

1

2

3