【发布时间】:2019-06-24 03:32:48
【问题描述】:
我正在寻找向当前导航栏添加一个活动元素类,但目前正在努力。
我已经尝试过 w3schools 方法,但可能我实现不正确。
代码:
// Get the container element
var btnContainer = document.getElementsByClassName("tab");
// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("link");
// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
#navbar {
position: absolute;
text-align: right;
top: 3.5em;
right: 3.5em;
z-index: 2;
}
.tab {
background-color: white;
opacity: 0.3;
height: 3.5em;
width: 0.2em;
margin-bottom: 1em;
}
.tab:hover{
opacity:1;
transition:0.7s ease;
}
.link:hover > .text {
opacity:1;
transition:0.7s ease;
}
.active, .tab:hover {
opacity:1;
transition:0.7s ease;
}
.active, .text:hover > .text {
opacity:1;
transition:0.7s ease;
}
<div id="navbar">
<div class="tab">
<a class="link active" href="#home">
<div class="text">Home</div>
</a></div>
<div class="tab">
<a class="link" href="#work">
<div class="text">Work</div>
</a></div>
<div class="tab">
<a class="link" href="#about">
<div class="text">About</div>
</a></div>
</div>
导航栏当前正在工作,但没有活动元素。我希望选项卡在活动时为 opacity: 1。
【问题讨论】:
-
tab不是id,它是一个类,getElementById不起作用 -
@CalvinNunes 我已将 'getElementById' 更改为 'getElementsByClassName' 但仍然不起作用 - 有什么想法吗?
-
“活动”是指悬停元素还是单击元素?
-
@CalvinNunes 我的意思是点击它:)
-
为什么评论说 'Get all button with class="btn" inside the container' 但你得到的是那些带有类“link”的按钮?
标签: javascript jquery html css hyperlink