You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击模态框关闭按钮时如何添加scale-out-center动画类?

Bootstrap模态框关闭动画修复

问题现象

点击模态框的“×”按钮时,模态框直接关闭无动画效果;再次打开模态框时,动画会在未点击任何按钮的情况下自动触发。

问题代码

CSS动画类

.scale-out-center {
   -webkit-animation: scale-out-center 0.3s cubic-bezier(0.550, 0.085, 0.680, 0.530) both;
    animation: scale-out-center 0.3s cubic-bezier(0.550, 0.085, 0.680, 0.530) both;
}

@-webkit-keyframes scale-out-center {
  0% {
    -webkit-transform: scale(1);
            transform: scale(1);
    opacity: 1;
  }
  100% {
    -webkit-transform: scale(0);
            transform: scale(0);
    opacity: 1;
  }
}
@keyframes scale-out-center {
  0% {
    -webkit-transform: scale(1);
            transform: scale(1);
    opacity: 1;
  }
  100% {
    -webkit-transform: scale(0);
            transform: scale(0);
    opacity: 1;
  }
}

原JavaScript代码

var hideDelay = true;
document.querySelector('#myModal').addEventListener('hide.bs.modal', function(e) {
    if (hideDelay) {
    document.querySelector('.modal-content').classList.add('scale-out-center');
    hideDelay = false;
    setTimeout(function() {
        document.querySelector('#myModal').modal('hide');
        document.querySelector('.modal-content').classList.remove('scale-out-center');
    }, 5000);
    return false;
    }
    hideDelay = true;
    return true;
});

修复方案

原代码核心问题:在hide.bs.modal事件中重复调用modal('hide')会循环触发事件,超时时间与动画时长不匹配,状态变量逻辑混乱。修改后的代码如下:

const modal = document.querySelector('#myModal');
const modalContent = document.querySelector('.modal-content');

modal.addEventListener('hide.bs.modal', function(e) {
    // 阻止默认关闭,先执行动画
    e.preventDefault();
    
    // 添加动画类触发缩放效果
    modalContent.classList.add('scale-out-center');
    
    // 监听动画结束,完成后再关闭模态框
    const handleAnimationEnd = () => {
        modalContent.classList.remove('scale-out-center');
        // 手动关闭模态框,避免重复触发hide事件
        modal.modal('hide');
        modalContent.removeEventListener('animationend', handleAnimationEnd);
    };
    
    modalContent.addEventListener('animationend', handleAnimationEnd);
});

// 模态框打开前移除动画类,避免自动触发
modal.addEventListener('show.bs.modal', function() {
    modalContent.classList.remove('scale-out-center');
});

修复说明

  • 阻止hide.bs.modal默认行为,优先执行动画
  • 用animationend事件替代固定超时,确保动画完全结束后再关闭模态框
  • 在模态框显示前强制移除动画类,避免再次打开时自动触发动画
  • 移除易引发逻辑混乱的hideDelay变量,改用事件监听控制流程

内容的提问来源于stack exchange,提问作者Bastion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:16:12