gif效果图:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>tab栏切换(可移除item)</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-size: 14px;
color: white;
}
body {
background-color: #333;
}
.tab {
margin: 20px auto;
list-style: none;
}
.item {
position: relative;
float: left;
padding: 10px;
background-color: #222;
border-top: 1px solid black;
border-bottom: 1px solid black;
cursor: pointer;
}
.item:nth-child(1) {
border-left: 1px solid black;
}
.item:nth-last-child(1) {
border-right: 1px solid black;
}
.active {
border-bottom: 0;
background-color: #333;
border-bottom-left-radius: -4px;
border-bottom-right-radius: -4px;
}
.close {
margin-left: 10px;
opacity: .3;
}
.close:hover {
background-color: #aaa7a7;
}
</style>
</head>
<body>
<ul class="tab">
<li class="item">菜单<span class="close">X</span></li>
<li class="item">菜单<span class="close">X</span></li>
<li class="item">菜单<span class="close">X</span></li>
<li class="item">菜单<span class="close">X</span></li>
<li class="item">菜单<span class="close">X</span></li>
<li class="item">菜单<span class="close">X</span></li>
<li class="item">菜单<span class="close">X</span></li>
<li class="item">菜单<span class="close">X</span></li>
<li class="item">菜单<span class="close">X</span></li>
<li class="item">菜单<span class="close">X</span></li>
<li class="item">菜单<span class="close">X</span></li>
</ul>
<script>
const tab = document.querySelector('.tab')
tab.addEventListener('click', ({ target }) => {
// 当前活跃tab
if (target.tagName === 'LI') {
let activeOld = document.querySelector('.active')
if (activeOld) {
activeOld.classList.remove('active')
let r = activeOld.nextElementSibling
if (r) r.style.borderBottomLeftRadius = '0px'
let l = activeOld.previousElementSibling
if (l) l.style.borderBottomRightRadius = '0px'
}
target.classList.add('active')
let nr = target.nextElementSibling
if (nr) nr.style.borderBottomLeftRadius = '5px'
let nl = target.previousElementSibling
if (nl) nl.style.borderBottomRightRadius = '5px'
}
// 移除tab
if (target.classList.contains('close')) {
const parent = target.parentElement
if (parent.classList.contains('active')) {
let r = parent.nextElementSibling
if (r) r.style.borderBottomLeftRadius = '0px'
let l = parent.previousElementSibling
if (l) l.style.borderBottomRightRadius = '0px'
}
parent.remove()
}
})
</script>
</body>
</html>