Пытаюсь добавить всплывающее окно на страницу веб-сайта, но JavaScript не заставляет всплывающее окно исчезать при нажатии

Обновлено: я скорректировал css и js, как было рекомендовано, и у меня все еще были проблемы, пока я не переместил скрипт в нижнюю часть моего html-документа прямо перед закрывающим тегом body. Я предполагаю, что перед попыткой запуска скрипта он не загружался полностью. ой! Огромное спасибо всем, кто помог мне ^^

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

Я попытался добиться этого, добавив CSS-свойство .click, которое сделает непрозрачность всплывающего окна равной 0, а затем добавив .click с помощью javascript. Искренне не уверен, что случилось, поэтому любая помощь приветствуется.

let popup = document.querySelector('.popup');
let close_button = document.querySelector('.close_button');
close_button.onclick = function() {
  popup.classList.add('.click');
}
.popup {
  display: flex;
  align-items: center;
  justify-content: center;
  transition: 0.2s;
}

.popup .click {
  opacity: 0;
  pointer-events: none;
}

.warning {
  display: flex;
  flex-direction: column;
  background-color: blue;
  padding: 1vh;
  margin-top: 5vh;
}

.heading {
  font-size: 60px;
  color: azure;
  padding-bottom: 1vh;
}

.message-box {
  background-color: azure;
  padding: 1vh;
}

.message {
  font-size: 24px;
  padding-bottom: 1vh;
}

.button-box {
  display: flex;
  align-items: center;
  justify-content: center;
}

.close_button {
  font-size: 24px;
  background-color: blue;
  color: azure;
  border: 0px;
  padding: 1vh;
  border-radius: 5px;
  transition: opacity 0.3s;
}

.close_button:hover {
  opacity: 0.7;
}

.close_button:active {
  opacity: 1;
}
<div class = "popup">
  <div class = "warning">
    <div class = "heading">Warning</div>
    <div class = "message-box">
      <div class = "message">This website contains mature content not suited for minors</div>
      <div class = "button-box">
        <button class = "close_button" type = "button">I am 18+</button>
      </div>
    </div>
  </div>
</div>

Я думаю, .popup .click в вашем CSS должно быть .popup.click без места. Я не проверял, но думаю, что это ваша проблема. Также лично я бы изменил его с opacity: 0 на просто display: none, но это только я.

async await 13.07.2024 08:17

Кроме того, это popup.classList.add('click'); не popup.classList.add('.click'); точка — это селектор CSS-запроса для класса, а не то, что вам нужно передать в имя класса.

async await 13.07.2024 08:19
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
1
2
51
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий
  1. Строка popup.classList.add('.click'); неверна. Должно быть popup.classList.add('click');

  2. Обновите селектор CSS на .popup.click, чтобы согласовать добавление классов и таргетинг селектора.

let popup = document.querySelector('.popup');
let close_button = document.querySelector('.close_button');
close_button.onclick = function() {
  popup.classList.add('click');
}
.popup {
  display: flex;
  align-items: center;
  justify-content: center;
  transition: 0.2s;
}

.popup.click {
  opacity: 0;
  pointer-events: none;
}

.warning {
  display: flex;
  flex-direction: column;
  background-color: blue;
  padding: 1vh;
  margin-top: 5vh;
}

.heading {
  font-size: 60px;
  color: azure;
  padding-bottom: 1vh;
}

.message-box {
  background-color: azure;
  padding: 1vh;
}

.message {
  font-size: 24px;
  padding-bottom: 1vh;
}

.button-box {
  display: flex;
  align-items: center;
  justify-content: center;
}

.close_button {
  font-size: 24px;
  background-color: blue;
  color: azure;
  border: 0px;
  padding: 1vh;
  border-radius: 5px;
  transition: opacity 0.3s;
}

.close_button:hover {
  opacity: 0.7;
}

.close_button:active {
  opacity: 1;
}
<div class = "popup">
  <div class = "warning">
    <div class = "heading">Warning</div>
    <div class = "message-box">
      <div class = "message">This website contains mature content not suited for minors</div>
      <div class = "button-box">
        <button class = "close_button" type = "button">I am 18+</button>
      </div>
    </div>
  </div>
</div>

С таким же успехом можно использовать <диалог>. Я добавил еще один <button> для пользователей младше 18 лет, который заставит браузер вернуться на предыдущую страницу (эта функция не будет работать во фрагменте). Подробности прокомментированы в примере ниже.

// Reference the <dialog> and the 2 <button>s
const popup = document.querySelector(".popup");
const exit = document.querySelector(".exit");
const close = document.querySelector(".close");

// Start with <dialog> open.
popup.showModal();

/*
  Register <button class = "exit"> to listen for the "click" event.
  When invoked, the browser will jump back to the previous page.
  This feature will not work from this Snippet.
*/
exit.addEventListener("click", function(e) {
  history.back();
});

/*
  Register <button class = "close"> to listen for the "click" event.
  When invoked, the <dialog> will close.
*/
close.addEventListener("click", function(e) {
  popup.close();
});
:root {
  font: 3vmin/1 "Segoe UI";
}

main {
  width: 100%;
}

/*
  The following styles animate the <dialog>
  https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog#animating_dialogs
*/
/* BEGIN */
.popup {
  border: 0;
  background: rgb(0 0 0 / 0%);
  opacity: 0;
  transform: scaleY(0);
  transition: 0.7s allow-discrete;
}

.popup[open] {
  opacity: 1;
  transform: scaleY(1);
}

@starting-style {
  .popup[open] {
    opacity: 0;
    transform: scaleY(0);
  }
}

.popup::backdrop {
  background: rgb(0 0 0 / 0%);
  transition: 0.7s allow-discrete;
}

.popup[open]::backdrop {
  background: rgb(0 0 0 / 50%);
}

@starting-style {
  .popup[open]::backdrop {
  background: rgb(0 0 0 / 50%);
  }
}
/* END */

.warning {
  margin-top: 10vh;
  padding: 0.25rem;
  border-radius: 8px;
  background: blue;
}

header {
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  padding: 0.25rem 1rem 0;
}

h4 {
  margin: 0;
  font-weight: 500;
  font-size: 4rem;
  color: white
}

.content {
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
  background: white;
}

.message {
  padding: 1rem 1rem 0;
  font-size: 2rem;
}

footer {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-bottom: 1.5rem;
  border-radius: 8px;
  background: white;
}

button {
  display: inline-block;
  width: 11ch;
  padding: 0.2rem 0.5rem 0.4rem;
  border-color: transparent;
  outline: none;
  font: inherit;
  font-size: 2rem;
  color: white;
  background: blue;
}

button:hover {
  opacity: 0.7;
  cursor: pointer;
}

button:active {
  opacity: 1;
}

.exit {
  border-color: blue;
  border-bottom-right-radius: 0;
  border-top-right-radius: 0;
  border-bottom-left-radius: 8px;
  border-top-left-radius: 8px;
  border-right: 1.5px inset #bbb;
  color: blue;
  background: white;
}

.close {
  border-bottom-left-radius: 0;
  border-top-left-radius: 0;
  border-bottom-right-radius: 8px;
  border-top-right-radius: 8px;
  border-left: 1.5px inset #bbb;
}
<dialog class = "popup">
  <section class = "warning">
    <header>
      <h4>Warning</h4>
    </header>
    <section class = "content">
      <p class = "message">This website contains mature content not suited for minors.</p>
      <footer>
        <button class = "exit">Under 18</button>
        <button class = "close">Over 17👍</button>
      </footer>
    </section>
  </section>
</dialog>

<main>
  <p>Let’s burn that lab to the ground. Friends don't lie. Nancy, seriously, you're gonna be so cool now, it's ridiculous. You're an idiot, Steve Harrington. You're beautiful, Nancy Wheeler.</p>
  <p> Friends don't lie. Nancy, seriously, you're gonna be so cool now, it's ridiculous. You're an idiot, Steve Harrington. You're beautiful, Nancy Wheeler. We never would've upset you if we knew you had superpowers.</p>
  <p> Nancy, seriously, you're gonna be so cool now, it's ridiculous. You're an idiot, Steve Harrington. You're beautiful, Nancy Wheeler. We never would've upset you if we knew you had superpowers. We never would've upset you if we knew you had superpowers.</p>
  <p> You're an idiot, Steve Harrington. You're beautiful, Nancy Wheeler. We never would've upset you if we knew you had superpowers. We never would've upset you if we knew you had superpowers. You’re going to be home by 8, listening to the Talking Heads
    and reading Vonnegut or something.</p>
  <p> You're beautiful, Nancy Wheeler. We never would've upset you if we knew you had superpowers. We never would've upset you if we knew you had superpowers. You’re going to be home by 8, listening to the Talking Heads and reading Vonnegut or something.
    That sounds like a nice night.</p>
  <p> We never would've upset you if we knew you had superpowers. We never would've upset you if we knew you had superpowers. You’re going to be home by 8, listening to the Talking Heads and reading Vonnegut or something. That sounds like a nice night. Mouth-breather.</p>
  <p> We never would've upset you if we knew you had superpowers. You’re going to be home by 8, listening to the Talking Heads and reading Vonnegut or something. That sounds like a nice night. Mouth-breather. So, Jonathan, how was the pull-out? Do you know
    anything about sensory deprivation tanks? Specifically how to build one?You are such a nerd.</p>
  <p>You’re going to be home by 8, listening to the Talking Heads and reading Vonnegut or something. That sounds like a nice night. Mouth-breather. So, Jonathan, how was the pull-out? Do you know anything about sensory deprivation tanks? Specifically how
    to build one? You are such a nerd. No wonder you only hang out with boys.</p>
  <p> That sounds like a nice night. Mouth-breather. So, Jonathan, how was the pull-out? Do you know anything about sensory deprivation tanks? Specifically how to build one?</p>
  <p>That sounds like a nice night. I need my paddles! Yeah, I want a date with Bo Derek. We all want things. It’s about the shadow monster, isn’t it? You’re going to take out the demigorgon with a slingshot? You are such a nerd. No wonder you only hang
    out with boys.</p>
  <p> I need my paddles! Yeah, I want a date with Bo Derek. We all want things. It’s about the shadow monster, isn’t it? You’re going to take out the demigorgon with a slingshot? You are such a nerd. No wonder you only hang out with boys. YOU BETTER RUN!</p>
  <p>She's our friend, and she's crazy! You are such a nerd. We all want things. It’s about the shadow monster, isn’t it? You’re going to take out the demigorgon with a slingshot? You are such a nerd. </p>
  <p>Bitchin' Let’s burn that lab to the ground. No. . . no El, you're not the monster. You saved me. Do you understand? You saved me. Mouth-breather. You’re right.</p>
  <p>Mouth-breather. You’re right. You are a freak…. Who would you rather be friends with: Bowie or Kenny Rogers? Why’s he gotta kick the door? Nobody normal ever accomplished anything meaningful in this world.</p>
  <p> You’re right. You are a freak…. Who would you rather be friends with: Bowie or Kenny Rogers?</p>
</main>

Другие вопросы по теме