javascript - 将活动类添加到当前元素
问题描述
我正在寻找向我当前的导航栏添加一个活动元素类,但目前正在苦苦挣扎。
我已经尝试过 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 。
解决方案
使用以下方法查看下面的快速 jQuery 解决方案:
- 。上()
- .closest()
- .addClass() 和
- .removeClass()
$(function() {
var links = $('.tab > .link');
links.on('click', function() {
links.removeClass('active').closest('.tab').removeClass('active');
$(this).addClass('active').closest('.tab').addClass('active');
})
.first().click();
});
#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">
<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>
推荐阅读
- java - 改造 - 解压缩 gzip
- amazon-web-services - 无法连接到部署在 AWS ECS 上的 GRPC 服务器
- sql - 在 T-SQL 中按条件排序
- python - Pandas - 检查每行的多列中是否存在一个值
- macos - Pydub 找不到 ffmpeg,尽管它已安装并在路径中
- django - 如何忽略生产中的一些迁移
- javascript - 如何首先将 div 高度从 auto 调整到 content 高度,然后用内容填充它,而不是相反?
- listview - TapGestureRecognizer 在 ListView 中不起作用
- powershell - 在 VSCode 中调试 PowerShell Azure 函数时出错
- python - 在python 3.7中将列表转换为用','分隔的字符串