#javascript #html
Не получается найти ошибку, почему класс не убирается при клике на элемент который
уже имеет этот класс
html:
panel 1
1 Anim pariatur cliche reprehenderit, enim eiusmod high life
accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard
dolor brunch..
panel 2
2 Anim pariatur cliche reprehenderit, enim eiusmod high life
accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard
dolor brunch.
js:
function ready() {
var panels = document.getElementsByClassName("panel");
var i;
for (i = 0; panels.length > i; i++) {
panels[i].onclick = function() {
for (i = 0; panels.length > i; i++) {
panels[i].classList.remove("active");
}
if (this.classList.contains("active")) {
this.classList.remove("active")
} else {
this.classList.add("active")
}
};
}
}
document.addEventListener("DOMContentLoaded", ready);
Ответы
Ответ 1
Можно обойтись и без циклов внутри обработчика. Функция getElementsByClassName возвращает живую коллекцию. Таким образом получив один раз коллекцию для класса active var actives = document.getElementsByClassName('active'); В ней всегда будут актуальные данные. И так как подразумевается только один активный элемент он будет доступен по индексу 0. Теперь в обработчике достаточно проверить, что был предыдущий активный элемент и убрать с него класс active var currentActive = actives[0]; if (currentActive) currentActive.classList.remove("active"); И если щелкнули не по активному элементу - нужно добавить этому элементу класс active if (currentActive !== this) this.classList.add("active"); Пример в сборе: var panels = document.getElementsByClassName("panel"); var actives = document.getElementsByClassName('active'); for (i = 0; panels.length > i; i++) { panels[i].onclick = function() { var currentActive = actives[0]; if (currentActive) currentActive.classList.remove("active"); if (currentActive !== this) this.classList.add("active"); }; } .active { border: solid 2px green; }panel 1
1 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch..
panel 2
2 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch.
Ответ 2
в цикле пропускать элемент, на который щелкнули т.e. for (i = 0; panels.length > i; i++) { if (panels[i] != this) panels[i].classList.remove("active"); }
Комментариев нет:
Отправить комментарий