- 在html中构建基本结构
内容如下
...其他代码
<body>
<div class="container">
<div id='tabBox'>
<div class="item">tab1</div>
<div class="item">tab22</div>
<div class="item">tab333</div>
<div class="item">tab4444</div>
</div>
</div>
</body>
...其他代码
- 构建基本样式
<style>
*{margin: 0;padding: 0;}
:root{--width:0;--left:0;}
html,body{width: 100vw;height: 100vh;}
.container{
background: #e0eaf7;
overflow: hidden;
height: 100%;
}
.container #tabBox{
margin: 0 auto;
display: flex;
width: 70vw;
justify-content: space-around;
margin-top: 150px;
border-radius: 24px;
position: relative;
border: 4px solid #fff;
}
.container #tabBox .item{
margin: 0;
padding: 10px 20px;
z-index: 10;
cursor: pointer;
}
.active{color:#fff}
#tabBox::before{
content: '';
height: 100%;
width: var(--width);
left: var(--left);
position: absolute;
background: #598bf0;
border-radius: 24px;
transition: all 0.4s ease-in-out;
}
</style>
- 在JS中实现点击切换
<script>
window.onload = function(){
var oParentDiv = document.getElementById('tabBox');
var oChildDiv = oParentDiv.getElementsByTagName('div');
var root = document.querySelector(':root');
function setCssVar(dom){
const {left,width} = dom.getBoundingClientRect()
const {left:parentLeft} = oParentDiv.getBoundingClientRect()
dom.className = 'item active'
root.style.setProperty('--width',width+'px')
root.style.setProperty('--left',left-parentLeft-5+'px')
}
setCssVar(oChildDiv[0])
for(let i = 0; i < oChildDiv.length;i++){
oChildDiv[i].onclick = function(){
for(let j = 0 ; j < oChildDiv.length; j++){
oChildDiv[j].className = 'item'
}
setCssVar(this)
}
}
}
</script>

有能继续优化点还望评论提点一下,谢谢~