我有一些针对多个按钮的Javascript代码。单击时,内容应该出现,它会出现。但是,我正在努力创建代码,当再次单击按钮时,内容将被隐藏。
我已经包含了我想要切换的元素的Javascript,内容和CSS。欢呼声。
注意:代码必须是Javascript
function openTab(click, openTab) {
var i, content, link;
content = document.getElementsByClassName("content");
for (i = 0; i < content.length; i++) {
content[i].style.display = "none";
}
links = document.getElementsByClassName("links");
for (i = 0; i < links.length; i++) {
links[i].className = links[i].className.replace(" active", "");
}
document.getElementById(openTab).style.display = "block";
click.currentTarget.className += " active";
}
.content {
font-family: 'Lato';
max-width: 100%;
font-size: 20px;
letter-spacing: 4px;
color: #e8eaed;
display: none;
border-top: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<section class = "Container">
<div class="tabs">
<button class="link" onclick="openTab(event, 'About')">About</button>
<button class="link" onclick="openTab(event, 'Hire')">Why You Should Hire Me</button>
<button class="link" onclick="openTab(event, 'Contact')">Contact</button>
</div>
</section>
<section class="Container2">
<div id="About" class="content">About</div>
<div id="Hire" class="content">Hire</div>
<div id="Contact" class="content">Contact</div>
</section>
答案 0 :(得分:1)
声明一个表示元素是否隐藏的变量。此外,您可以尝试使用classList
来添加/删除具有多个类名的元素中的类,而不是className
字符串操作(如果可能的话)。
您可以使用classList.toggle轻松切换课程:
let hidden = false;
function openTab(click, openTabId) {
document.querySelectorAll('.content').forEach(
content => content.style.display = hidden ? 'block' : 'none'
);
document.querySelectorAll('.links').forEach(
link => link.classList.toggle('active')
);
document.getElementById(openTabId).style.display = "block";
click.currentTarget.classList.toggle('active');
hidden = !hidden;
}
更好的是,将hidden
变量封装在openTab
中,因为它在外部范围内无效:
const openTab = (() => {
let hidden = false;
return (click, openTabId) => {
document.querySelectorAll('.content').forEach(
content => content.style.display = hidden ? 'block' : 'none'
);
document.querySelectorAll('.links').forEach(link => {
if (hidden) link.classList.add('active');
else link.classList.remove('active');
});
document.getElementById(openTabId).style.display = "block";
click.currentTarget.classList.toggle('active');
hidden = !hidden;
}
})();