Я могу заставить div исчезать при нажатии, но как мне сделать так, чтобы он исчезал?

Я работал над созданием этой страницы TOS, но столкнулся с проблемой анимации появления и исчезновения.

Я заставил div исчезать при нажатии кнопки, но не знаю, как сделать так, чтобы он исчезал при повторном нажатии кнопки. Любые советы будут полезны

https://jsfiddle.net/MakkerHeineken/khs8b43f/1/

function unhideTOS() {
  document.getElementById("text").style.display = "";
}

function unlockBTN() {
  document.getElementById("text").style.display = "";
}

function scrollToAccept() {
  const terms = document.querySelector('.terms-and-conditions');
  const button = document.querySelector('.accept');
  // const watch = document.querySelector('.watch');

  if (!terms) {
    return; // quit function because there is no terms
  }

  // fires on page load because can't find element
  function obCallback(payload) {
    // console.info(payload[0].isIntersecting); // whether element is in view or not
    // console.info(payload[0].intersectionRatio); // how much of the element is showing
    if (payload[0].intersectionRatio === 1) {
      button.disabled = false;
      // stop observing the last element
      ob.unobserve(terms.lastElementChild);
    }
  }

  // takes in callback parameter
  // will be called every time it needs to check if something is currently on the page
  // watcher (needs to be told what to watch
  const ob = new IntersectionObserver(obCallback, {
    root: terms,
    threshold: 1,
  });

  // call observe method on what we want to watch
  // ob.observe(watch);
  ob.observe(terms.lastElementChild);

}
scrollToAccept();

$('.yes').on('click', function(e) {
  e.preventDefault();
  $('.TOSHIDE').toggleClass('active');
  //$(this).parents('ul').next().toggleClass('active');
})
body {
  background: #ffffff;
}

.wrapper-all {
  min-height: 94vh;
  display: grid;
  justify-content: center;
  align-content: center;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  line-height: 2;
}

.wrapper {
  width: 400px;
  height: 80vh;
  padding: 20px;
  border: 1px solid black;
  background: white;
  display: grid;
  grid-template-rows: 1fr auto;
}

button {
  background: #133C55;
  color: white;
  font-size: 1rem;
  padding: 20px;
  transition: opacity 0.2s;
}

button[disabled] {
  opacity: 0.1;
  /* transform: translateX(-300%) scale(0.5); */
}

.terms-and-conditions {
  overflow: scroll;
}

footer {
  background-color: #192718;
  width: 100%;
  padding: 8px 0;
  margin-top: 8px;
}

footer .container {
  width: 800px;
  margin: 0 auto;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

footer .container a {
  color: #fff;
}

footer a:hover {
  color: #fce26a;
}

.tacbox {
  display: block;
  padding: 1em;
  margin: 2em;
  border: 3px solid #ddd;
  background-color: #eee;
  max-width: 800px;
}

input {
  height: 2em;
  width: 2em;
  vertical-align: middle;
}

.TOSHIDE {
  display: none;
}

.TOSHIDE.active {
  display: block;
  opacity: 1;
}

.fade-in-image {
  animation: fadeIn 5s;
  -webkit-animation: fadeIn 5s;
  -moz-animation: fadeIn 5s;
  -o-animation: fadeIn 5s;
  -ms-animation: fadeIn 5s;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@-moz-keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@-webkit-keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@-o-keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@-ms-keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.fade-out {
  animation: fadeOut ease 5s;
  animation-fill-mode: forwards;
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<head>
  <script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>

<body>
  <div class = "tacbox">
    <!-- The code for the checkbox + download if checked. -->
    I agree to these &zwnj;<a href = "#tos" class = "yes">Terms and Conditions.</a>
    <br>
    <a id = "text" style = "display:none" href = "file.doc" Download>Download!</a>
  </div>

  <div class = "TOSHIDE fade-in-image">
    <div class = "wrapper-all">
      <div class = "wrapper">
        <div class = "terms-and-conditions">
          <h1>Terms and Conditions</h1>
          <p>Disclaimer THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. You are the Current Maintainer of the Software, and to permit recipients of the Licensed Product for any such warranty, support,
            indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so in a commercial product offering.</p>
          <hr>
        </div>
        <button class = "accept" disabled autocomplete = "off" id = "myCheck" onclick = "unlockBTN()">Accept</button>
      </div>
    </div>
  </div>
</body>

К вашему сведению, jQuery 1.7 был выпущен в 2011. Вы можете рассмотреть возможность обновления.

isherwood 16.03.2022 16:41

См. Как спросить. Вы включили сюда гораздо больше кода, чем необходимо для демонстрации вашей проблемы.

isherwood 16.03.2022 16:42
Поведение ключевого слова "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) для оценки ваших знаний,...
3
2
88
4
Перейти к ответу Данный вопрос помечен как решенный

Ответы 4

сделал код для переключателя, который вам, вероятно, не нужен. Основная часть — это анимация затухания:

//toggle var
var fade_state = true;
//on btn click
function fade() {
  //get the button and div
  let div = document.getElementById("div");
  let btn = document.getElementById("fade");
  //if faded in or out
  if (fade_state == true) {
    //trigers animation
    div.style.animation = "fade-out 2s forwards";
    //sets the text
    btn.innerHTML = "fade-in";
    //sets fade_state
    fade_state = false;
  } else if (fade_state == false) {
    //trigers animation
    div.style.animation = "fade-in 2s forwards";
    //sets the text
    btn.innerHTML = "fade-out";
    //sets fade_state
    fade_state = true;
  }
}
div {
  width: 30vw;
  height: 30vh;
  background-color: blue;
  opacity: 100%;
}


/*the fade animations*/

@keyframes fade-out {
  from {
    opacity: 100%;
  }
  to {
    opacity: 0%;
  }
}

@keyframes fade-in {
  from {
    opacity: 0%;
  }
  to {
    opacity: 100%;
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta charset = "utf-8">
  <meta name = "viewport" content = "width=device-width">
  <title>fade-in_fade-out</title>
  <link href = "style.css" rel = "stylesheet" type = "text/css" />
</head>

<body>
  <button id = "fade" onclick = "fade()">fade-out</button>
  <div class = "main" id = "div">some text</div>
  <script src = "script.js"></script>
</body>

</html>

Когда вы используете jQuery, вы можете использовать метод исчезатьToggle. Для вашего кода просто замените $('.TOSHIDE').toggleClass('active'); в вашем JavaScript на $('.TOSHIDE').fadeToggle(); и немного поиграйте с параметрами продолжительности.

Ответ принят как подходящий

Более простой подход с использованием анимации jQuery, без анимации CSS.

function scrollToAccept() {
  const terms = document.querySelector('.terms-and-conditions');
  const button = document.querySelector('.accept');
  // const watch = document.querySelector('.watch');

  if (!terms) {
    return; // quit function because there is no terms
  }

  // fires on page load because can't find element
  function obCallback(payload) {
    // console.info(payload[0].isIntersecting); // whether element is in view or not
    // console.info(payload[0].intersectionRatio); // how much of the element is showing
    if (payload[0].intersectionRatio === 1) {
      button.disabled = false;
      // stop observing the last element
      ob.unobserve(terms.lastElementChild);
    }
  }

  // takes in callback parameter
  // will be called every time it needs to check if something is currently on the page
  // watcher (needs to be told what to watch
  const ob = new IntersectionObserver(obCallback, {
    root: terms,
    threshold: 1,
  });

  // call observe method on what we want to watch
  // ob.observe(watch);
  ob.observe(terms.lastElementChild);

}
scrollToAccept();

$('.yes').on('click', function(e) {
  e.preventDefault();
  $('.TOSHIDE').fadeToggle(3000).toggleClass('active');
  //$(this).parents('ul').next().toggleClass('active');
});
body {
  background: #ffffff;
}

.wrapper-all {
  min-height: 94vh;
  display: grid;
  justify-content: center;
  align-content: center;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  line-height: 2;
}

.wrapper {
  width: 400px;
  height: 80vh;
  padding: 20px;
  border: 1px solid black;
  background: white;
  display: grid;
  grid-template-rows: 1fr auto;
}

button {
  background: #133C55;
  color: white;
  font-size: 1rem;
  padding: 20px;
  transition: opacity 0.2s;
}

button[disabled] {
  opacity: 0.1;
  /* transform: translateX(-300%) scale(0.5); */
}

.terms-and-conditions {
  overflow: scroll;
}

footer {
  background-color: #192718;
  width: 100%;
  padding: 8px 0;
  margin-top: 8px;
}

footer .container {
  width: 800px;
  margin: 0 auto;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

footer .container a {
  color: #fff;
}

footer a:hover {
  color: #fce26a;
}

.tacbox {
  display: block;
  padding: 1em;
  margin: 2em;
  border: 3px solid #ddd;
  background-color: #eee;
  max-width: 800px;
}

input {
  height: 2em;
  width: 2em;
  vertical-align: middle;
}

.TOSHIDE {
  display: none;
}

.TOSHIDE.active {
  display: block;
  opacity: 1;
}
<!DOCTYPE html>
<html lang = "en">

<head>
  <meta charset = "UTF-8">
  <meta http-equiv = "X-UA-Compatible" content = "IE=edge">
  <meta name = "viewport" content = "width=device-width, initial-scale=1.0">
  <title>Terms of Service</title>
  <link rel = "stylesheet" href = "./scroll-to-accept.css" />
  <link rel = "stylesheet" href = "style.css">
  <script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>

<body>

  <script>
    function unhideTOS() {
      document.getElementById("text").style.display = "";
    }
  </script>

  <script>
    function unlockBTN() {
      document.getElementById("text").style.display = "";
    }
  </script>

  <div class = "tacbox">
    <!-- The code for the checkbox + download if checked. -->
    I agree to these &zwnj;<a href = "#tos" class = "yes">Terms and Conditions.</a>
    <br>
    <a id = "text" style = "display:none" href = "file.doc" Download>Download!</a>
  </div>

  <div class = "TOSHIDE">
    <div class = "wrapper-all">
      <div class = "wrapper">
        <div class = "terms-and-conditions">
          <h1>Terms and Conditions</h1>
          <p>Disclaimer THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. You are the Current Maintainer of the Software, and to permit recipients of the Licensed Product for any such warranty, support,
            indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so in a commercial product offering.</p>
          <hr>
        </div>
        <button class = "accept" disabled autocomplete = "off" id = "myCheck" onclick = "unlockBTN()">Accept</button>
      </div>
    </div>
  </div>
  <script src = "./scroll-to-accept.js"></script>
</body>

</html>

с CSS анимацией

function scrollToAccept() {
  const terms = document.querySelector('.terms-and-conditions');
  const button = document.querySelector('.accept');
  // const watch = document.querySelector('.watch');

  if (!terms) {
    return; // quit function because there is no terms
  }

  // fires on page load because can't find element
  function obCallback(payload) {
    // console.info(payload[0].isIntersecting); // whether element is in view or not
    // console.info(payload[0].intersectionRatio); // how much of the element is showing
    if (payload[0].intersectionRatio === 1) {
      button.disabled = false;
      // stop observing the last element
      ob.unobserve(terms.lastElementChild);
    }
  }

  // takes in callback parameter
  // will be called every time it needs to check if something is currently on the page
  // watcher (needs to be told what to watch
  const ob = new IntersectionObserver(obCallback, {
    root: terms,
    threshold: 1,
  });

  // call observe method on what we want to watch
  // ob.observe(watch);
  ob.observe(terms.lastElementChild);

}
scrollToAccept();

$('.yes').on('click', function(e) {
    e.preventDefault();
    if ($('.TOSHIDE').hasClass('fade-in-image')) {
        $('.TOSHIDE').toggleClass('fade-in-image').toggleClass('fade-out');
      }
      else if ($('.TOSHIDE').hasClass('fade-out')) {
        $('.TOSHIDE').toggleClass('fade-out').toggleClass('fade-in-image');
      } else {
        $('.TOSHIDE').toggleClass('fade-in-image');
      }
  });
body {
  background: #ffffff;
}

.wrapper-all {
  min-height: 94vh;
  display: grid;
  justify-content: center;
  align-content: center;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  line-height: 2;
}

.wrapper {
  width: 400px;
  height: 80vh;
  padding: 20px;
  border: 1px solid black;
  background: white;
  display: grid;
  grid-template-rows: 1fr auto;
}

button {
  background: #133C55;
  color: white;
  font-size: 1rem;
  padding: 20px;
  transition: opacity 0.2s;
}

button[disabled] {
  opacity: 0.1;
  /* transform: translateX(-300%) scale(0.5); */
}

.terms-and-conditions {
  overflow: scroll;
}

footer {
  background-color: #192718;
  width: 100%;
  padding: 8px 0;
  margin-top: 8px;
}

footer .container {
  width: 800px;
  margin: 0 auto;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

footer .container a {
  color: #fff;
}

footer a:hover {
  color: #fce26a;
}

.tacbox {
  display: block;
  padding: 1em;
  margin: 2em;
  border: 3px solid #ddd;
  background-color: #eee;
  max-width: 800px;
}

input {
  height: 2em;
  width: 2em;
  vertical-align: middle;
}

.TOSHIDE {
  opacity: 0;
}

.fade-in-image {
  animation: fadeIn 5s;
  -webkit-animation: fadeIn 5s;
  -moz-animation: fadeIn 5s;
  -o-animation: fadeIn 5s;
  -ms-animation: fadeIn 5s;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@-moz-keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@-webkit-keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@-o-keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@-ms-keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.fade-out {
  animation: fadeOut ease 5s;
  animation-fill-mode: forwards;
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<!DOCTYPE html>
<html lang = "en">

<head>
  <meta charset = "UTF-8">
  <meta http-equiv = "X-UA-Compatible" content = "IE=edge">
  <meta name = "viewport" content = "width=device-width, initial-scale=1.0">
  <title>Terms of Service</title>
  <link rel = "stylesheet" href = "./scroll-to-accept.css" />
  <link rel = "stylesheet" href = "style.css">
  <script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>

<body>

  <script>
    function unhideTOS() {
      document.getElementById("text").style.display = "";
    }
  </script>

  <script>
    function unlockBTN() {
      document.getElementById("text").style.display = "";
    }
  </script>

  <div class = "tacbox">
    <!-- The code for the checkbox + download if checked. -->
    I agree to these &zwnj;<a href = "#tos" class = "yes">Terms and Conditions.</a>
    <br>
    <a id = "text" style = "display:none" href = "file.doc" Download>Download!</a>
  </div>

  <div class = "TOSHIDE">
    <div class = "wrapper-all">
      <div class = "wrapper">
        <div class = "terms-and-conditions">
          <h1>Terms and Conditions</h1>
          <p>Disclaimer THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. You are the Current Maintainer of the Software, and to permit recipients of the Licensed Product for any such warranty, support,
            indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so in a commercial product offering.</p>
          <hr>
        </div>
        <button class = "accept" disabled autocomplete = "off" id = "myCheck" onclick = "unlockBTN()">Accept</button>
      </div>
    </div>
  </div>
  <script src = "./scroll-to-accept.js"></script>
</body>

</html>

Есть ли конкретная причина, по которой мы не просто переключаем класс css и используем переходы? Вы можете просто переключить класс в обертке div и настроить все, что вам нравится. Я не уверен, что понимаю необходимость всех сценариев.

.fade-in {
  animation: fadeIn ease 10s;
  -webkit-animation: fadeIn ease 10s;
  -moz-animation: fadeIn ease 10s;
  -o-animation: fadeIn ease 10s;
  -ms-animation: fadeIn ease 10s;
}
@keyframes fadeIn {
  0% {
    opacity:0;
  }
  100% {
    opacity:1;
  }
}

@-moz-keyframes fadeIn {
  0% {
    opacity:0;
  }
  100% {
    opacity:1;
  }
}

@-webkit-keyframes fadeIn {
  0% {
    opacity:0;
  }
  100% {
    opacity:1;
  }
}

@-o-keyframes fadeIn {
  0% {
    opacity:0;
  }
  100% {
    opacity:1;
  }
}

@-ms-keyframes fadeIn {
  0% {
    opacity:0;
  }
  100% {
    opacity:1;
}

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