Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

html - How to use transition/animation when changing visibility with JavaScript?

I want the dropdown to fade in and out onclick using JavaScript but now it′s just appearing and disapearing quickly.

    function toggleDropdown() {
        var x = document.getElementById("myDropdown");
    
        if (x.style.visibility === "visible") {
          x.style.visibility = "hidden";
        } else {
          x.style.visibility = "visible";
      
        }
      }
 #myDropdown{
           visibility: hidden;
           // -webkit-animation: fadeinout 4s linear forwards;
           // animation: fadeinout 4s linear forwards;
           transition: visibility 1s linear 300ms, visibility 300ms;
        }
        <div class="dropdown" id="dropdown">
          <button onclick="toggleDropdown()">Choose connection</button>
          <div id="myDropdown">
            <img src="images/searchicon.png" alt="">
            <input type="text" placeholder="">
            <a href="">Base</a>
            <a href="#blog">Blog</a>
          </div>
        </div>
question from:https://stackoverflow.com/questions/65933840/how-to-use-transition-animation-when-changing-visibility-with-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Edit: fix visibility

function toggleDropdown() {
  var x = document.getElementById("myDropdown");
  if (x.style.opacity === "1") {
    x.style.opacity = "0";
    x.style.visibility = "hidden";
  } 
  else {
    x.style.opacity = "1";
    x.style.visibility = "visible";
  }
}
#dropdown {
  height:20px;
}
#myDropdown {
  visibility:hidden;
  opacity:0;
  transition:visibility 0.3s linear,opacity 0.3s linear;
}
<div class="dropdown" id="dropdown">
    <!-- <a href="#">Open Menu</a> -->
    <button onclick="toggleDropdown()">Choose connection</button>
    <div id="myDropdown">
      <img src="images/searchicon.png" alt="">
      <input type="text" placeholder="">
      <a href="">Base</a>
      <a href="#blog">Blog</a>
    </div>
  </div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...