我正在尝试创建简单的标签,我的目标是用红色边框强调当前标签。默认情况下,我的父div带有灰色边框。我要达到的目的是选中按钮的红色边框应覆盖灰色的边框:
.tab {
width: 150px;
border-bottom: 2px solid red;
}
.tabs {
width: 1000px;
padding-bottom: 18px;
border-bottom: 2px solid grey;
}
<div class="tabs">
<button class="tab">New</button>
<button class="tab">Archive</button>
</div>
有没有一种方法可以在不更改结构的情况下实现它?
答案 0 :(得分:2)
我建议您提供一个具有正确属性的类selected
并使用js切换
POC:
const tabs = document.querySelectorAll(".tab");
document.addEventListener("click", (e) => {
if (e.target.classList.contains("tab")) {
for (const tab of tabs) {
tab.classList.remove("selected");
}
e.target.classList.add("selected");
}
});
.tab {
width: 150px;
border-bottom: 2px solid grey;
}
.tab.selected {
border-bottom: 2px solid red;
}
.tabs {
width: 1000px;
padding-bottom: 18px;
}
<div class="tabs">
<button class="tab selected">New</button>
<button class="tab">Archive</button>
</div>
答案 1 :(得分:0)
如果不需要Edge和IE支持,请使用focus:within
:
.tab {
width: 150px;
border-bottom: 2px solid red;
}
.tabs {
width: 1000px;
padding-bottom: 18px;
border-bottom: 2px solid grey;
}
.tabs:focus-within {
border-color: red;
}
<div class="tabs">
<button class="tab">New</button>
<button class="tab">Archive</button>
</div>
答案 2 :(得分:0)
对代码进行了一些更改,以使选项卡显示活动状态和非活动状态。请在下面查找代码。
$(document).ready(function(){
$('.tab.active').parent().addClass('tab-active');
$('.tab').click(function(){
$('.tab').removeClass('active');
$(this).addClass('active')
});
});
.tab {
width: 150px;
border-bottom: 2px solid grey;
}
.tab.active,.tabs.tab-active {
border-bottom-color: red;
}
.tabs {
width: 1000px;
padding-bottom: 18px;
border-bottom: 2px solid grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tabs">
<button class="tab active">New</button>
<button class="tab">Archive</button>
</div>