Animate.css搭配Bootstrap 4 Modal:关闭动画bounceOutLeft失效求助
Hey there! I totally get the frustration when one part of your animation setup works but the other doesn’t—let’s get that bounceOutLeft close animation working for your Bootstrap modal.
The core issue here is that Bootstrap’s modal hides itself immediately when you trigger the close action, which cuts off the Animate.css animation before it can run. We need to override that default behavior to let the animation finish first. Here’s how to do it:
Step 1: Adjust Your Modal HTML
Make sure your modal’s dialog element has the base Animate.css class, so we can dynamically add/remove animation classes later:
<div class="modal fade" id="yourModal" tabindex="-1" role="dialog"> <div class="modal-dialog animate__animated" role="document"> <!-- Add base animation class here --> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Your Modal Title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> Your modal content goes here </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div>
Step 2: Add Custom JavaScript to Control Animations
We’ll hook into Bootstrap’s modal events to manage the animation flow properly:
const modal = document.getElementById('yourModal'); const modalDialog = modal.querySelector('.modal-dialog'); // Handle open animation modal.addEventListener('show.bs.modal', function () { // Clear any leftover close animation classes modalDialog.classList.remove('animate__bounceOutLeft'); // Add the open animation modalDialog.classList.add('animate__rubberBand'); }); // Handle close animation modal.addEventListener('hide.bs.modal', function (e) { // Stop Bootstrap from hiding the modal right away e.preventDefault(); // Add the close animation class modalDialog.classList.add('animate__bounceOutLeft'); // Wait for the animation to finish before hiding the modal modalDialog.addEventListener('animationend', function cleanup() { // Remove this listener so it doesn't fire multiple times modalDialog.removeEventListener('animationend', cleanup); // Manually hide the modal and clean up Bootstrap's backdrop modal.classList.remove('show'); modalDialog.classList.remove('animate__bounceOutLeft'); document.querySelector('.modal-backdrop').remove(); document.body.classList.remove('modal-open'); document.body.style.paddingRight = ''; }); });
Quick Tips to Avoid Issues:
- Always remove old animation classes before adding new ones to prevent conflicts.
- We use
animationendto ensure the full animation plays out before the modal disappears. - The manual cleanup of the backdrop and body classes is necessary because we stopped Bootstrap’s default close behavior.
This setup should make both your rubberBand open animation and bounceOutLeft close animation run smoothly!
内容的提问来源于stack exchange,提问作者Julez

