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 }) => {// 当前活跃tabif (target.tagName === 'LI') {let activeOld = document.querySelector('.active')if (activeOld) {activeOld.classList.remove('active')let r = activeOld.nextElementSiblingif (r) r.style.borderBottomLeftRadius = '0px'let l = activeOld.previousElementSiblingif (l) l.style.borderBottomRightRadius = '0px'}target.classList.add('active')let nr = target.nextElementSiblingif (nr) nr.style.borderBottomLeftRadius = '5px'let nl = target.previousElementSiblingif (nl) nl.style.borderBottomRightRadius = '5px'}// 移除tabif (target.classList.contains('close')) {const parent = target.parentElementif (parent.classList.contains('active')) {let r = parent.nextElementSiblingif (r) r.style.borderBottomLeftRadius = '0px'let l = parent.previousElementSiblingif (l) l.style.borderBottomRightRadius = '0px'}parent.remove()}})</script>
</body></html>