Кнопка закрытия формы не работает с JavaScript - PullRequest
0 голосов
/ 11 апреля 2020

Я создал кнопку X, чтобы закрыть форму с Javascript, но она не работает, и я не могу понять, почему. Как только я открываю это, я не могу закрыться. Я просто размещаю здесь код для кнопки и формы, а не всю страницу за ней. Надеюсь, кто-нибудь может мне помочь.

html

<div class="open-btn">
  <button id="show-modal"><strong>Open Form</strong></button>
</div>
<div class="modal modal--hidden">
 <div class="modal_content">
        <div class="close"> 
          <i class="fas fa-times">X</i>
        </div>
        <h1>Ask away</h1>
        <form id="submit">
      <input type="text" placeholder="Name">
      <input type="email" id="email" placeholder="Email">
      <input type="text" placeholder="Subject">
      <textarea placeholder="Message"></textarea>
      <button>Submit</button>
    </form>
  </div>
</div>

css

#show-modal {
  border: none;
  border-bottom: 2px solid rgb(48, 51, 54);
  cursor: pointer;
  color: rgb(48, 51, 54);
  padding: 5px;
  font-family: "Lato", sans-serif;
  letter-spacing: 0.1em;
  font-size: 13px;
  line-height: 1.4;
}
.open-btn {
  padding-top: 30px;
}


.modal {
  background-color: rgb(0, 0, 0, 0.8);
  position: absolute;
  top: 0;
  height: 1000px;
  width: 100%;
  display: none;
  justify-content: center;
  align-items: center;
}

.modal_content {
  background-color: #fff;
  padding: 2rem 4rem;
  width: 500px;
  height: 450px;
  border-radius: 4px;
}

input[type="text"],
input[type="email"],
textarea {
  width: 100%;
  padding: 0.5rem;
  display: block;
  margin: 15px auto;
  border: none;
  border-bottom: 1px solid #000000;
}
textarea {
  height: 100px;
}

.modal_content h1 {
  font-family: "Ibarra Real Nova", serif;
  color: rgba(40, 44, 48, 1);
  font-weight: bold;
  text-align: center;
  font-size: 35px;
}
.close {
  display: flex;
  justify-content: flex-end;
  margin-right: -2rem;
  margin-top: -1rem;
  cursor: pointer;
}
.submit {
  width: 100%;
  padding: 0.5rem;
  background-color: rgba(234, 203, 193, 0.4);
  border: none;
  color: #fff;
  transition: all 0.3s ease;
}
.submit:hover {
  background-color: rgba(143, 126, 121, 0.4);
}

.modal--hidden {
  display: none;
} 

JavaScript

document.getElementById("show-modal").addEventListener("click", function() {
  document.querySelector(".modal").style.display = "flex";
});
document.querySelector(".fas fa-times").addEventListener("click", function() {
  document.querySelector(".modal").style.dispay = "none";
});

https://codepen.io/joanaoli09/pen/JjYoZoa

Ответы [ 5 ]

1 голос
/ 11 апреля 2020

Проблема в вашем втором приемнике событий:

вы пытаетесь получить элемент по ".fa fa-times", который не является допустимым селектором для вашего кросс-элемента.

Просто замените ".fa fa-times" с ".fa.fa-times или ".fa-times", и он должен прекрасно работать.

document.querySelector(".fa-times").addEventListener("click", function() {
  document.querySelector(".modal").style.display = "none";
});
1 голос
/ 11 апреля 2020

у вас есть две ошибки о закрытии события. один из них - ваше имя класса, вам нужно написать fa-times, другой - вы написали, что это неправильно

document.querySelector(".fa-times").addEventListener("click", function() {
  console.log("casa")
   document.querySelector(".modal").style.display = "none";

});
1 голос
/ 11 апреля 2020

Сначала ваша позиция клика и X были другими. Хотя вы прикрепляли событие к i, но нажимали на X. В этом случае поместите X как текст i. Во-вторых, оно должно быть document.querySelector(".fas.fa-times") вместо document.querySelector(".fas fa-times") и в-третьих использовать classList.toggle вместо добавления класса к атрибуту стиля

document.getElementById("show-modal").addEventListener("click", function() {
  togglElementeClass();
});
document.querySelector(".fas.fa-times").addEventListener("click", function() {
  togglElementeClass();
});

function togglElementeClass() {
  document.querySelector(".modal").classList.toggle('flex');
}
#show-modal {
  border: none;
  border-bottom: 2px solid rgb(48, 51, 54);
  cursor: pointer;
  color: rgb(48, 51, 54);
  padding: 5px;
  font-family: "Lato", sans-serif;
  letter-spacing: 0.1em;
  font-size: 13px;
  line-height: 1.4;
}

.open-btn {
  padding-top: 30px;
}

.modal {
  background-color: rgb(0, 0, 0, 0.8);
  position: absolute;
  top: 0;
  height: 1000px;
  width: 100%;
  display: none;
  justify-content: center;
  align-items: center;
}

.modal_content {
  background-color: #fff;
  padding: 2rem 4rem;
  width: 500px;
  height: 450px;
  border-radius: 4px;
}

input[type="text"],
input[type="email"],
textarea {
  width: 100%;
  padding: 0.5rem;
  display: block;
  margin: 15px auto;
  border: none;
  border-bottom: 1px solid #000000;
}

textarea {
  height: 100px;
}

.modal_content h1 {
  font-family: "Ibarra Real Nova", serif;
  color: rgba(40, 44, 48, 1);
  font-weight: bold;
  text-align: center;
  font-size: 35px;
}

.close {
  display: flex;
  justify-content: flex-end;
  margin-right: -2rem;
  margin-top: -1rem;
  cursor: pointer;
}

.submit {
  width: 100%;
  padding: 0.5rem;
  background-color: rgba(234, 203, 193, 0.4);
  border: none;
  color: #fff;
  transition: all 0.3s ease;
}

.submit:hover {
  background-color: rgba(143, 126, 121, 0.4);
}

.modal--hidden {
  display: none;
}

.flex {
  display: flex;
}

.fas.fa-times {
  width: 20px;
  height: 20px;
  border: 1px solid green;
}
<div class="open-btn">
  <button id="show-modal"><strong>Open Form</strong></button>
</div>
<div class="modal modal--hidden">
  <div class="modal_content">
    <div class="close">
      <i class="fas fa-times">X</i>
    </div>
    <h1>Ask away</h1>
    <form id="submit">
      <input type="text" placeholder="Name">
      <input type="email" id="email" placeholder="Email">
      <input type="text" placeholder="Subject">
      <textarea placeholder="Message"></textarea>
      <button>Submit</button>
    </form>
  </div>
</div>
0 голосов
/ 11 апреля 2020

document.getElementById("show-modal").addEventListener("click", function() {
  document.querySelector(".modal").style.display = "flex";
});
function closeMe() {
  document.querySelector(".modal").style.display = "none";
}
#show-modal {
  border: none;
  border-bottom: 2px solid rgb(48, 51, 54);
  cursor: pointer;
  color: rgb(48, 51, 54);
  padding: 5px;
  font-family: "Lato", sans-serif;
  letter-spacing: 0.1em;
  font-size: 13px;
  line-height: 1.4;
}
.open-btn {
  padding-top: 30px;
}


.modal {
  background-color: rgb(0, 0, 0, 0.8);
  position: absolute;
  top: 0;
  height: 1000px;
  width: 100%;
  display: none;
  justify-content: center;
  align-items: center;
}

.modal_content {
  background-color: #fff;
  padding: 2rem 4rem;
  width: 500px;
  height: 450px;
  border-radius: 4px;
}

input[type="text"],
input[type="email"],
textarea {
  width: 100%;
  padding: 0.5rem;
  display: block;
  margin: 15px auto;
  border: none;
  border-bottom: 1px solid #000000;
}
textarea {
  height: 100px;
}

.modal_content h1 {
  font-family: "Ibarra Real Nova", serif;
  color: rgba(40, 44, 48, 1);
  font-weight: bold;
  text-align: center;
  font-size: 35px;
}
.close {
  display: flex;
  justify-content: flex-end;
  margin-right: -2rem;
  margin-top: -1rem;
  cursor: pointer;
}
.submit {
  width: 100%;
  padding: 0.5rem;
  background-color: rgba(234, 203, 193, 0.4);
  border: none;
  color: #fff;
  transition: all 0.3s ease;
}
.submit:hover {
  background-color: rgba(143, 126, 121, 0.4);
}

.modal--hidden {
  display: none;
} 
<div class="open-btn">
  <button id="show-modal"><strong>Open Form</strong></button>
</div>
<div class="modal modal--hidden">
 <div class="modal_content">
        <div class="close"> 
          <i class="fas fa-times" onclick="closeMe()">X</i>
        </div>
        <h1>Ask away</h1>
        <form id="submit">
      <input type="text" placeholder="Name">
      <input type="email" id="email" placeholder="Email">
      <input type="text" placeholder="Subject">
      <textarea placeholder="Message"></textarea>
      <button>Submit</button>
    </form>
  </div>
</div>
0 голосов
/ 11 апреля 2020

Прежде всего, получение элементов общими классами, такими как fas fa, которые предоставляют сторонние библиотеки (в этом случае font-awesome), не является хорошей практикой. Потому что можно использовать те же классы для другого элемента на странице. Я предлагаю использовать идентификатор для этой ситуации или специфицированный c класс. Другая проблема заключается в том, что мы обычно используем <button> для действий, а не <i>. <i> тег не готов к действию, поэтому, щелкая по нему, вы фактически нажимаете на его содержимое (X), а не на тег. Теперь проблема в вашем коде состоит в том, что когда вы устанавливаете display: flex в JS, элемент получает стиль, а когда вы document.querySelector(".modal").style.dispay = "none";, вы не очищаете предыдущий стиль (display: flex), поэтому они оба применяются. Вы должны очистить display: flex, затем применить display: none или создать класс, подобный d-flex, который переключается при нажатии.

In HTML

<div class="close">
  <i id="close-btn" class="fas fa-times">X</i>
</div>

In CSS

.d-flex
{
  display:flex !important;
}

In Js

document.getElementById("show-modal").addEventListener("click", function() {
  togglElementeClass();
});
document.querySelector("#close-btn").addEventListener("click", function() {
  togglElementeClass();
});

function togglElementeClass() {
  document.querySelector(".modal").classList.toggle('d-flex');
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...