我正在寻找向我当前的导航栏添加一个事件元素类,但目前正在苦苦挣扎。
我试过 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>
导航栏当前正在工作,但没有事件元素。我希望选项卡在事件时不透明度为 1。
最佳答案
首先,您需要将类添加到父级 div,而不是链接,因为它是将不透明度设置为 0.3 的父级。现在,我在 jQuery
中完成了它,因为它更容易实现。希望这不是问题。
$('.link').on('click', function() {
$('.link').parent().removeClass('active');
$(this).parent().addClass('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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="navbar">
<div class="tab active">
<a class="link" 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>
关于javascript - 将事件类添加到当前元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54447600/