最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Show and hide with CSS animation - Stack Overflow

programmeradmin2浏览0评论

My goal is to create an animation when showing and hiding an HTML element. The show and hide is triggered by a button that toggles a class hide.

Here is my code:

const button = document.querySelector('button');
const box = document.querySelector('.box');

button.addEventListener('click', () => {
  box.classList.toggle('hide');
})
.box {
  width:200px;
  height: 200px;
  border: 1px solid #000;
  background-color: gray;
  margin: 0 auto;
  opacity: 1;
  display: block;  
}

.hide {
  display: none;
  transition: all 1s ease-out;
  opacity: 0;  
}
<button>Show / Hide</button>
<div class="box hide"></div>

My goal is to create an animation when showing and hiding an HTML element. The show and hide is triggered by a button that toggles a class hide.

Here is my code:

const button = document.querySelector('button');
const box = document.querySelector('.box');

button.addEventListener('click', () => {
  box.classList.toggle('hide');
})
.box {
  width:200px;
  height: 200px;
  border: 1px solid #000;
  background-color: gray;
  margin: 0 auto;
  opacity: 1;
  display: block;  
}

.hide {
  display: none;
  transition: all 1s ease-out;
  opacity: 0;  
}
<button>Show / Hide</button>
<div class="box hide"></div>

Share Improve this question asked Apr 29, 2022 at 19:53 Maik LowreyMaik Lowrey 17.6k7 gold badges53 silver badges99 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

If you want to use animations do not use display:none, you can use visibility

const button = document.querySelector('button');
const box = document.querySelector('.box');

button.addEventListener('click', () => {
  box.classList.toggle('hide');
})
.box {
  width:200px;
  height: 200px;
  border: 1px solid #000;
  background-color: gray;
  margin: 0 auto;
  opacity: 1;
  transition: all 1s ease-out;
  visibility: visible;  
}

.hide {
  visibility: hidden;
  transition: all 1s ease-out;
  opacity: 0;  
}
<button>Show / Hide</button>
<div class="box hide"></div>

just remove the display: block from your hide and if you want animated went div show add the animation too:

const button = document.querySelector('button');
const box = document.querySelector('.box');

button.addEventListener('click', () => {
  box.classList.toggle('hide');
})
.box {
  width:200px;
  height: 200px;
  border: 1px solid #000;
  background-color: gray;
  margin: 0 auto;
  opacity: 1;
  transition: all 1s ease-out;
  display: block;  
}

.hide {
  transition: all 1s ease-out;
  opacity: 0;  
}
<button>Show / Hide</button>
<div class="box hide"></div>

I had the same goal but I couldn't find the answer here. I hope my code can help other people.

Note: I can edit it if you need it.

My code :

<!DOCTYPE html>
<html lang="fr" style="position: absolute; top: 0; left: 0; font-size: 16px; margin: 0; padding: 0; width: 100%;">
  <head>
    <title>Div reveal test</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content='width=device-width, initial-scale=1' name='viewport'/>
  </head>
  <body style="margin: 0; padding: 0; width: 100%; background: #90ee90;">
    <style>
      div.hidden-stuff-container {
        overflow-y: hidden;
        overflow-x: scroll;
        width: calc(100% - 40px);
        margin: 10px;
        padding: 10px;
        background: rgba(0, 0, 0, 0.1);
        transition: all 1s;
      }
      div.hidden-stuff-title {
        display: inline-block;
        margin: 0;
        padding: 0;
      }
      span.hidden-stuff-arrow {
        transform: rotate(45deg);
        border-top: 1px solid black;
        border-left: 1px solid black;
        display: inline-block;
        width: 10px;
        height: 10px;
        position: relative;
        top: 5px;
        transition: all 1s;
      }
      button.hidden-stuff-button {
        display: inline-block;
        font-family: initial;
        font-size: 1rem;
        border: none;
        border-radius: 0%;
        padding: 5px;
        margin: 0;
        background: rgba(0, 0, 0, 0);
      }
      button.hidden-stuff-button:hover {
        background:rgba(0, 0, 0, 0.1);
      }
      div.hidden-stuff {
        display: none;
        opacity: 0;
        transition: all 1s;
        margin: 0;
        padding: 10px;
        background:rgba(255, 255, 255, 0.2);
      }
    </style>
    <script type="text/javascript">
      async function show_hidden_stuff(hidden_stuff_id){
        let hidden_stuff_container = document.getElementById(hidden_stuff_id + '-container');
        let hidden_stuff_container_initial_size = document.getElementById(hidden_stuff_id + '-title').offsetHeight;
        let hidden_stuff_container_current_size = hidden_stuff_container.offsetHeight - 20;//-20 because of padding
        let hidden_stuff_arrow = document.getElementById(hidden_stuff_id + '-arrow');
        let hidden_stuff = document.getElementById(hidden_stuff_id);
        let hidden_stuff_container_max_size;
        if(hidden_stuff.style.display == 'block'){
          if(hidden_stuff_container.style.height == 'auto'){//Wait for the openning to end
            //It's required that the div has a fixed size for the animation to work
            hidden_stuff_container.style.height = hidden_stuff_container_current_size + 'px';
            //And it's also somehow required to wait
            await new Promise(wait=>setInterval(wait, 1));
            hidden_stuff.style.opacity = '0';
            hidden_stuff_arrow.style.top = '5px';
            hidden_stuff_arrow.style.transform = 'rotate(45deg)';
            hidden_stuff_container.style.height = hidden_stuff_container_initial_size + 'px';
            await new Promise(wait=>setInterval(wait, 1000));
            hidden_stuff.style.display = 'none';
          }
        }
        else{
          hidden_stuff_container.style.height = hidden_stuff_container_initial_size + 'px';
          hidden_stuff.style.display = 'block';
          //It's somehow required to wait after setting display from none to block for opacity transition to work
          await new Promise(wait=>setInterval(wait, 1));
          hidden_stuff.style.opacity = '1';
          hidden_stuff_arrow.style.top = '-2px';
          hidden_stuff_arrow.style.transform = 'rotate(-135deg)';
          hidden_stuff_container_max_size = hidden_stuff_container_initial_size + hidden_stuff.offsetHeight;
          hidden_stuff_container.style.height = hidden_stuff_container_max_size + 'px';
          await new Promise(wait=>setInterval(wait, 1000));
          //Allow dynamic resizing (ex: when we turn our phone)
          hidden_stuff_container.style.height = 'auto';
        }
      }
    </script>
    <div class="hidden-stuff-container" id="somestuff-container">
      <div class="hidden-stuff-title" id="somestuff-title"><button class="hidden-stuff-button" onclick="show_hidden_stuff('somestuff')">TITLE&#160;&#160;<span class="hidden-stuff-arrow" id="somestuff-arrow"></span></button></div>
      <div class="hidden-stuff" id="somestuff">
        TEXT
      </div>
    </div>
    <div class="hidden-stuff-container" id="anotherone-container">
      <div class="hidden-stuff-title" id="anotherone-title"><button class="hidden-stuff-button" onclick="show_hidden_stuff('anotherone')">Lorem ipsum&#160;&#160;<span class="hidden-stuff-arrow" id="anotherone-arrow"></span></button></div>
      <div class="hidden-stuff" id="anotherone">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ac tellus volutpat, viverra ligula vel, placerat lorem. Donec nunc ex, pretium et eros vel, posuere pretium velit. Fusce id modo neque, eu tincidunt dui. Aliquam at ex pellentesque velit interdum fermentum sed at arcu. Vivamus at mauris justo. Cras ornare eleifend ullamcorper. Morbi dapibus semper aliquet.</p>
        <p>Nam eget quam non enim pellentesque blandit at ut urna. Nam dapibus risus eu libero venenatis dapibus. Cras a turpis eu leo luctus ornare in eu nulla. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum ultricies risus ligula, eu hendrerit dui auctor quis. Donec non tempor nulla, sed accumsan lectus. Proin a metus varius, luctus odio at, dapibus lectus. Nunc a ornare turpis. Phasellus eget hendrerit ex, eget modo augue.</p>
        <p>Nullam euismod egestas risus et lacinia. Suspendisse potenti. Ut sed libero enim. Sed pretium at nisi ut convallis. Sed at magna non metus tincidunt pretium. Etiam ac scelerisque elit. Suspendisse potenti.</p>
        <p>Curabitur purus lacus, lacinia nec sapien vel, maximus consectetur augue. Ut imperdiet malesuada odio, in vulputate mauris facilisis vel. Interdum et malesuada fames ac ante ipsum primis in faucibus. Praesent vitae lacinia ante. Quisque semper ex lacus, non accumsan mi.</p>
      </div>
    </div>
  </body>
</html>

发布评论

评论列表(0)

  1. 暂无评论