我正在制作移動選單。我想換班. 第一步有效,它洗掉了“fa-bars”類并添加了“fa-times”。但是第二步不起作用。
<div class="menuToggle">
<i id='test' class="fas fa-bars fa-2x"></i>
</div>
let menuActive = document.querySelectorAll('.menuToggle i')
var element = document.getElementById('test');
if(element.classList.contains('fa-bars')){
function Activemenu(){
menuActive.forEach((item) =>
item.classList.remove('fa-bars'));
this.classList.add('fa-times');
}
}else if(element.classList.contains('fa-bars')){
function Activemenu(){
menuActive.forEach((item) =>
item.classList.remove('fa-times'));
this.classList.add('fa-bars');
}
}
menuActive.forEach((item) =>
item.addEventListener('click',Activemenu));
uj5u.com熱心網友回復:
那里有幾個問題:
您在
if/else塊中使用函式宣告。這些現在在某些有限的情況下(您的代碼不匹配)是標準化的,但它足夠復雜,您真的只想避免在塊中使用函式宣告。改為使用分配給變數的函式運算式。您正在為事件處理程式使用箭頭函式,但期望
this通過呼叫函式的方式來設定。箭頭函式不能那樣作業。您正在檢查
fa-bars這兩項classList.contains檢查。你可能想要fa-times第二個。您只是將第一個事件處理程式系結到該元素。當條件發生變化時,不會更新處理程式。
順便說一句,我建議for-of在forEach回呼上使用回圈:
const menuActive = document.querySelectorAll(".menuToggle i");
const element = document.getElementById("test");
function activeMenuClickHandler() {
if (element.classList.contains("fa-bars")) {
for (const item of menuActive) {
item.classList.remove("fa-bars"));
}
this.classList.add("fa-times");
} else if (element.classList.contains("fa-times")) {
for (const item of menuActive) {
item.classList.remove("fa-times"));
)
this.classList.add("fa-bars");
}
}
for (const item of menuActive) {
item.addEventListener("click", activeMenuClickHandler);
}
(或類似的,你可能需要做一些進一步的調整。)
如果此代碼僅切換fa-bars/ fa-times,則使用以下toggle功能可能會更簡單classList:
const menuActive = document.querySelectorAll(".menuToggle i");
const element = document.getElementById("test");
function activeMenuClickHandler() {
this.classList.toggle("fa-bars fa-times");
for (const item of menuActive) {
item.classList.toggle("fa-bars fa-times");
}
}
for (const item of menuActive) {
item.addEventListener("click", activeMenuClickHandler);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/405545.html
標籤:
上一篇:前N個不同的列值
