我正在处理一个遗留系统,我无法重写整个 CSS。
因此,我发现自己需要在单击另一个元素时在同一元素上切换 2 个类(想象一下单击按钮来隐藏/显示模式)。
以下是模式的代码。
模态窗口默认为 .hidden
(不带“visible”类),单击时为 .visible
(不带“hidden”类)。
function openModal(modalID) {
document.getElementById(modalID)
.classList.toggle('hidden');
document.getElementById(modalID)
.classList.toggle('visible');
}
I agree to accept the
<a href="#"
onclick="openModal('tandcmodal')">
terms and conditions
</a>
of this website.
<div id="tandcmodal"
class="hidden">
Content of the modal
</div>
所以,我相信一定有一种方法可以使用 .toggle()
同时切换多个类。
或者不是吗?
最佳答案
不幸的是,.toggle
accepts only one argument :您想要切换的一个类名称。为了做到 DRY,您必须迭代类名数组,或者将 classList 保存在变量中并调用 .toggle
两次:
function openModal(modalID) {
const { classList } = document.getElementById(modalID);
classList.toggle('hidden');
classList.toggle('visible');
}
.hidden {
display: none;
}
.visible {
display: block;
}
I agree to accept the
<a href="#" onclick="openModal('tandcmodal')">
terms and conditions
</a> of this website.
<div id="tandcmodal" class="hidden">
Content of the modal
</div>
但请注意,通常不需要同时使用隐藏
类和可见
类。通常,您可以仅仅一个hidden
类,然后添加/删除它,让默认显示样式在hidden
未激活时生效:
function openModal(modalID) {
document.getElementById(modalID).classList.toggle('hidden');
}
.hidden {
display: none;
}
I agree to accept the
<a href="#" onclick="openModal('tandcmodal')">
terms and conditions
</a> of this website.
<div id="tandcmodal" class="hidden">
Content of the modal
</div>
另请注意,内联属性处理程序的行为 very奇怪的是,存在转义问题,并且通常被认为是非常糟糕的做法 - 在几乎所有情况下都应该避免它们。考虑使用 Javascript 添加事件监听器:
document.querySelector('a').addEventListener('click', () => openModal('tandcmodal'));
function openModal(modalID) {
document.getElementById(modalID).classList.toggle('hidden');
}
.hidden {
display: none;
}
I agree to accept the
<a href="#">
terms and conditions
</a> of this website.
<div id="tandcmodal" class="hidden">
Content of the modal
</div>
关于javascript - Vanilla JS(无 jQuery) - 如何同时切换多个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60086357/