簡體   English   中英

Vanilla JS(無 jQuery) - 如何一次切換多個類?

[英]Vanilla JS (no jQuery) - How to toggle more than one class at once?

我正在處理一個遺留系統,我無法重寫整個 css。

因此,當單擊另一個類時,我發現自己需要在同一元素上切換 2 個類(想象一下單擊按鈕以隱藏/顯示模態)。

以下是模態的代碼。
凡模態窗口在默認情況下.hidden (無類“可見”),並點擊它.visible (無類“隱藏”)。

 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 只接受一個參數:您希望切換的一個類名。 為了 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類和visible類。 通常,您可以擁有一個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>

另請注意,內聯屬性處理程序的行為非常奇怪,存在轉義問題,並且通常被認為是非常糟糕的做法 - 在幾乎所有情況下都應該避免使用它們。 考慮使用 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM