简体   繁体   中英

Javascript - Reversing a Modal Animation

I have a few items on a site I'm building that onclick activate a modal like this .

Right now the animation is a one-way in that, when you close it or click off from the modal's focus, it just disappears. From what I've been reading, people seems to use the fadeIn/slideIn animation for one time effects, but is it possible, to reverse the animation so instead of just changing display to none, it slides back out?

#modal{bottom: 0; opacity: 1; transition: bottom 400ms, opacity 400ms; }
#modal.hidden{bottom: -300px; opacity: 0}

Then in button click event:

$("#modal").addClass("hidden")

On close event:

$("#modal").removeClass("hidden")

If you need pure javascript, it would be a bit more code but essentially that's it

Depending on how you've structured your code, you can approach this in a few ways:

  • Make use of the animation-direction: reverse; CSS property
  • Use a Javascript framework (like jQuery) that enables manipulation of DOM elements (with jQuery you could do something like: $('element').slideIn(); to show the modal and $('element').slideOut(); to hide the modal).
  • Use CSS classes and apply / unapply them with Javascript (the option I'd recommend, and have given an example below):

 $(document).ready(function() { $('.open').on('click', function(e) { e.preventDefault(); if ($('.modal').hasClass('hide')) { $('.modal').removeClass('hide'); } $('.modal').addClass('show'); }); $('.close').on('click', function(e) { e.preventDefault(); $('.modal').addClass('hide'); if ($('.modal').hasClass('show')) { $('.modal').removeClass('show'); } }); }); 
 .modal { position: fixed; top: 0; left: 0; width: 300px; height: 300px; left: -305px; z-index: 999; transition: all 0.3s ease; background: #ffffff; border: 1px solid blue; } .modal.show { left: 150px; } .modal.hide { left: -305px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Click <a href="#" class="open">here</a> to open modal</p> <div class="modal"> <p>This is a modal window.</p> <p>Click <a href="#" class="close">here</a> to close</p> </div> 

Please note that this example is only there to illustrate a proof of concept - you'll need to tidy it yourself :)

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