简体   繁体   中英

How to add Transition Effects to JavaScript toggle menu?

I want to give a smooth transition effect (like the ease in out or fade) to a simple JavaScript toggle mobile menu.

I have tried it achieving by CSS Transition effect but no luck but I am sure it can be either achieved by CSS or JavaScript. I think using CSS would be better unless it's impossible.

Here is the code:

var toggle  = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function() {
  content.style.display = (content.dataset.toggled ^= 1) ? "block" : "none";
});
#content{
  display:none;
}
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>

The content should be Show/Hide smoothly with ease in out or fade in/out effect. How is it possible?

here is your requiured solution. Jquery makes your task easy and understandable.

 var toggle = document.getElementById("toggle"); var content = document.getElementById("content"); $(document).ready(function(){ $("#toggle").click(function(){ $("#content").fadeToggle("slow"); /* $("#div3").fadeOut(3000); */ }); }); 
 #content { width:80px; height:80px; background-color:blue; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="toggle">TOGGLE</button> <div id="content">Some content...</div> 

You cannot animate display: none , because you remove the element entirely. Instead you could try and use a combination of visibility: visible --> visibility: hidden , and opacity: 1 --> opacity: 0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM