6

Не получается найти ошибку, почему класс не убирается при клике на элемент который уже имеет этот класс html:

       <div class="panel">
            <div class="panel-heading"><h4>panel 1</h4></div>
            <div class="panel-collapse">
                <div class="panel-body">
                    <p>1 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch..</p>
                </div>
            </div>
        </div>
        <div class="panel">
            <div class="panel-heading"><h4>panel 2</h4></div>
            <div class="panel-collapse">
                <div class="panel-body">
                    <p>2 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch.</p>
                </div>
            </div>
        </div>

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
  • действительно, спасибо, потратил мин 30 из-за этого )
    – dmitriy
    12 фев 2017 в 18:11

2 ответа 2

8

Можно обойтись и без циклов внутри обработчика.

Функция 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;
}
<div class="panel">
  <div class="panel-heading">
    <h4>panel 1</h4>
  </div>
  <div class="panel-collapse">
    <div class="panel-body">
      <p>1 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch..</p>
    </div>
  </div>
</div>
<div class="panel">
  <div class="panel-heading">
    <h4>panel 2</h4>
  </div>
  <div class="panel-collapse">
    <div class="panel-body">
      <p>2 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch.</p>
    </div>
  </div>
</div>

5

в цикле пропускать элемент, на который щелкнули

т.e.

for (i = 0; panels.length > i; i++) {
  if (panels[i] != this)
    panels[i].classList.remove("active");
}
2
  • чтото не так, если мы кликаем на панель, то эта должна открыться а остальные панели закрыться, но если на нее же кликнуть, то она должна закрыться
    – dmitriy
    12 фев 2017 в 18:19
  • @DimaVleskov с помощью кнопки "Фрагмент кода на ..." создайте, пожалуйста, в Вашем вопросе работающий пример, в котором "что-то не так"
    – user176262
    12 фев 2017 в 19:34

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.