js 原生手写tabs标签页
效果:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container{
width:400px;
height:400px;
margin: 100px auto;
border:1px solid red;
}
#a{
width:100%;
height:60px;
display: flex;
}
#a div{
flex-grow: 1;
display: flex;
align-items: center;
justify-content: center;
border:1px solid red;
}
.content{
width:100%;
height:340px;
background-color: rgba(16, 25, 122, 0.6);
display: none;
}
.container .active{
display: block;
}
</style>
</head>
<body>
<div class="container">
<div id="a">
<div>111</div>
<div>222</div>
<div>333</div>
<div>444</div>
</div>
<div class="content active">111</div>
<div class="content">222</div>
<div class="content">333</div>
<div class="content">444</div>
</div>
<script>
var a = document.getElementById('a');
var divObj = a.children
var content = document.getElementsByClassName('content')
for(var i = 0; i < divObj.length; i++){
divObj[0].style.backgroundColor = 'red'
divObj[i].setAttribute('index',i) //设置自定义属性
divObj[i].onclick = function(){
for(var j = 0; j < divObj.length; j++){
divObj[j].style.backgroundColor = '#fff'
content[j].classList.remove('active') //移除class
}
this.style.backgroundColor = "red"
content[this.getAttribute('index')].classList.add('active') //添加class
}
}
</script>
</body>
</html>