最近做项目接到了这么一个需求,页面上会有1-5个tab,要求这五个tab的宽度自适应,激活状态的tab宽度是未激活状态tab宽度的1.3倍,其余未激活状态的tab宽度必须等宽,并且要实现宽度变化的动画效果。(css和原生js实现)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
body {
background-color: #000;
}
.tab-wrap {
width: 100%;
position: absolute;
top: 282px;
display: flex;
}
.tab {
padding: 9px 0;
background: #fff;
opacity: 0.6;
font-weight: 400;
font-size: 14px;
line-height: 18px;
border-radius: 90px;
margin-right: 8px;
text-align: center;
color: #333;
flex: 1;
cursor: pointer;
transition: all 0.3s;
}
.tab:nth-last-child(1) {
margin-right: 0;
}
.tab.active {
flex: 1.3;
text-align: center;
background: #fff;
font-weight: 500;
opacity: 1;
}
</style>
</head>
<body>
<div class="tab-wrap">
<div class="tab active">bilibili</div>
<div class="tab">小红书</div>
<div class="tab">拼夕夕</div>
<div class="tab">得物</div>
<div class="tab">美团</div>
</div>
<script>
let tab = document.getElementsByClassName('tab')
let children = document.getElementsByClassName('tab-wrap')[0].children
for(let i = 0; i < tab.length; i++) {
tab[i].onclick = function(e) {
for(let j = 0; j < children.length; j++) {
children[j].classList.remove('active')
}
e.target.classList.add('active')
}
}
</script>
</body>
</html>