0

На странице есть кастомные инпуты-чекбоксы и дропдауны, для последних написан код, позволяющий закрывать их по клику вне их области, но из-за него не работает :checked у инпутов. Как исправить скрипт, чтобы все осталось работоспособным?

document.querySelectorAll(".header__dropdown-link").forEach(el => {
  el.addEventListener("click", (ev) => {
    ev.preventDefault();
    ev.stopPropagation();
    fnCloseAllDropdown(ev.target.nextElementSibling);
    ev.target.nextElementSibling.classList.toggle("painting-style__dropdown_show");
  });
});

document.addEventListener("click", (ev) => {
  if (ev.target.closest(".painting-style__dropdown_show")) return;
  ev.preventDefault();
  ev.stopPropagation();
  fnCloseAllDropdown();
});

function fnCloseAllDropdown(obj) {
  document.querySelectorAll(".painting-style__dropdown").forEach(el => {
    if (el != obj) {
      el.classList.remove("painting-style__dropdown_show");
    }
  });
}
.list-reset {
  margin: 0;
  padding: 0;
  list-style: none;
}


.publications__label {
  position: relative;
  display: inline-block;
}

.publications__input {
  position: absolute;
  opacity: 0;
}

.publications__span {
  display: flex;
  align-items: center;
  margin-left: 30px;
  line-height: 1;
  cursor: pointer;
}

.publications__span::before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  display: inline-block;
  width: 12px;
  height: 12px;
  border: 1px solid #000;
}

.publications__span::after {
  content: "";
  display: inline-block;
  position: absolute;
  left: 5px;
  top: 5px;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background-color: #c283f3;
  opacity: 0;
}

.publications__input:checked+.publications__span {
  color: red;
}

.publications__input:checked+.publications__span::after {
  opacity: 1;
}

.publications__input:focus+.publications__span {
  outline: 3px solid red;
  color: blue
}
<h3 class="publications__left-column-subheading white-font">Категории</h3>
<ul class="list-reset publications__list-categories">
  <li class="publications__list-item">
    <label class="publications__label prime-text white-font">
       <input class="publications__input" type="checkbox" />
       <span class="publications__span prime-text white-font">Бестселлеры</span>
    </label>
  </li>
  <li class="publications__list-item">
    <label class="publications__label prime-text white-font">
       <input class="publications__input" type="checkbox" />
       <span class="publications__span prime-text white-font">Искусство</span>
     </label>
  </li>
</ul>

1
  • 1
    ev.preventDefault(); ev.stopPropagation(); - так до инпута же событие click не доходит, каким образом ему :checked изменять?
    – nazarpunk
    13 окт 2021 в 9:34

2 ответа 2

1

Ваши скрипты никоем образом не влияют на чекбоксы. Ваша проблема что span накрывает input(видно на изображении) и вы не может епо нему кликнуть, просто добавьте z-index для скрытых input Еще бы неплохо было бы их выровнять

введите сюда описание изображения

document.querySelectorAll(".header__dropdown-link").forEach(el => {
  el.addEventListener("click", (ev) => {
    ev.preventDefault();
    ev.stopPropagation();
    fnCloseAllDropdown(ev.target.nextElementSibling);
    ev.target.nextElementSibling.classList.toggle("painting-style__dropdown_show");
  });
});

document.addEventListener("click", (ev) => {
  if (ev.target.closest(".painting-style__dropdown_show")) return;
  ev.preventDefault();
  ev.stopPropagation();
  fnCloseAllDropdown();
});

function fnCloseAllDropdown(obj) {
  document.querySelectorAll(".painting-style__dropdown").forEach(el => {
    if (el != obj) {
      el.classList.remove("painting-style__dropdown_show");
    }
  });
}
.list-reset {
  margin: 0;
  padding: 0;
  list-style: none;
}


.publications__label {
  position: relative;
  display: inline-block;
}

.publications__input {
  position: absolute;
  opacity: 0;
  z-index: 1;
}

.publications__span {
  display: flex;
  align-items: center;
  margin-left: 30px;
  line-height: 1;
  cursor: pointer;
}

.publications__span::before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  display: inline-block;
  width: 12px;
  height: 12px;
  border: 1px solid #000;
}

.publications__span::after {
  content: "";
  display: inline-block;
  position: absolute;
  left: 5px;
  top: 5px;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background-color: #c283f3;
  opacity: 0;
}

.publications__input:checked+.publications__span {
  color: red;
}

.publications__input:checked+.publications__span::after {
  opacity: 1;
}

.publications__input:focus+.publications__span {
  outline: 3px solid red;
  color: blue
}
<h3 class="publications__left-column-subheading white-font">Категории</h3>
<ul class="list-reset publications__list-categories">
  <li class="publications__list-item">
    <label class="publications__label prime-text white-font">
       <input class="publications__input" type="checkbox" />
       <span class="publications__span prime-text white-font">Бестселлеры</span>
    </label>
  </li>
  <li class="publications__list-item">
    <label class="publications__label prime-text white-font">
       <input class="publications__input" type="checkbox" />
       <span class="publications__span prime-text white-font">Искусство</span>
     </label>
  </li>
</ul>

1
  • там должна появиться фиолетовая точка на :сhecked, у вас так и не появилась. Для z-index не обязательно абсолют, подойдет и relative. Дело было в этом -ev.preventDefault(); в средней части скрипта, убрал и заработало)
    – Summersby
    13 окт 2021 в 14:06
0

Помогла построчная отладка этого кода:

document.querySelectorAll(".header__dropdown-link").forEach(el => {
  el.addEventListener("click", (ev) => {
    ev.preventDefault();
    ev.stopPropagation();
    fnCloseAllDropdown(ev.target.nextElementSibling);
    ev.target.nextElementSibling.classList.toggle("painting-style__dropdown_show");
  });
});

document.addEventListener("click", (ev) => {
  if (ev.target.closest(".painting-style__dropdown_show")) return;
  ev.preventDefault();//проблема была здесь, удалив эту строку, все заработало
  ev.stopPropagation();
  fnCloseAllDropdown();
});

function fnCloseAllDropdown(obj) {
  document.querySelectorAll(".painting-style__dropdown").forEach(el => {
    if (el != obj) {
      el.classList.remove("painting-style__dropdown_show");
    }
  });
}

Ваш ответ

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

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