# sweetalert2 响应式的弹窗和对话框 **Repository Path**: ren3016/sweetalert2 ## Basic Information - **Project Name**: sweetalert2 响应式的弹窗和对话框 - **Description**: SweetAlert2 是一个流行的开源 JavaScript 库,用于在网页中创建美观、响应式的弹窗和对话框。SweetAlert2 可以用来替代浏览器默认的提示框(如 alert、confirm 和 prompt),使得开发者可以展示更加定制化和吸引用户的交互元素。 - **Primary Language**: JavaScript - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-09-15 - **Last Updated**: 2026-04-13 ## Categories & Tags **Categories**: Uncategorized **Tags**: sweetalert ## README # sweetalert2 响应式的弹窗和对话框 ## 介绍 SweetAlert2 是一个流行的开源 JavaScript 库,用于在网页中创建美观、响应式的弹窗和对话框。SweetAlert2 可以用来替代浏览器默认的提示框(如 alert、confirm 和 prompt),使得开发者可以展示更加定制化和吸引用户的交互元素。 主要特点包括: - 多种类型的弹窗:支持信息提示、成功、错误、警告等多种预设类型。 - 高度可定制化:允许自定义文本、图标、按钮文字、背景颜色、宽度等。 - 异步操作支持:可以轻松地处理确认和取消事件,非常适合与异步函数结合使用。 - 丰富的配置选项:通过设置不同的参数,可以灵活控制弹窗的行为和外观。 - 移动端友好:设计时考虑了对移动设备的良好支持。 - 国际化:支持多语言,可以轻松更改按钮文本以适应不同语言需求。 ## 资源下载 ### sweetalert2 网站,查看教程及演示效果 更多:例子、特定任务代码示例、安装、用法、集成、配置参数、声明性模板、操作按钮、点击按钮后返回的Promise对象处理、图标、输入类型、方法 等官方说明。 [https://sweetalert2.github.io/](https://sweetalert2.github.io/) ### sweetalert2 在 github.com 只下载需要的资源就行 [https://github.com/sweetalert2/sweetalert2/releases](https://github.com/sweetalert2/sweetalert2/releases) ![下载资源](images/down.png) ## 安装教程 ### 方法1、在HTML中引入网络资源 ```html ``` ### 方法2、在HTML中引入本地资源 ```html ``` --- ## 使用说明 ### 🔸 sweetalert2 默认弹框样式,禁止点击遮罩层关闭弹窗,进制ESC关闭 ```html SweetAlert2 本地示例 ``` ![sweetalert2 默认弹框样式,禁止点击遮罩层关闭弹窗,进制ESC关闭](images/alert001.png) ### 🔸 最基本的弹框 ```javascript Swal.fire("SweetAlert2 is working!"); ``` ![最基本的弹框](images/alert001-2.png) ### 🔸 黑暗模式,不显示图标 ```javascript function successBtn() { Swal.fire({ title: '操作成功!', text: '数据已保存。', theme: 'dark', confirmButtonText: '确定', }); } ``` ![黑暗模式,不显示图标](images/alert002.png) ### 🔸 只显示标题 ```javascript function successBtn() { Swal.fire({ title: '操作成功!', confirmButtonText: '确定', }); } ``` ![只显示标题](images/alert003.png) ### 🔸 只显示内容,显示按钮“取消” ```javascript function successBtn() { Swal.fire({ text: '操作成功!', showConfirmButton: false, showCancelButton: true, cancelButtonText: '取消', }); } ``` ![只显示内容,显示按钮“取消”](images/alert004.png) ### 🔸 不显示按钮 ```javascript function successBtn() { Swal.fire({ text: '操作成功!', showConfirmButton: false, showCancelButton: false, }); } ``` ![不显示按钮](images/alert005.png) ### 🔸 自定义mask过渡背景色 ```javascript function successBtn() { Swal.fire({ title: '操作成功!', confirmButtonText: '确定', backdrop: ` radial-gradient(circle, rgba(63,94,251,0.75) 0%, rgba(70,253,131,0.69) 100%) ` }); } ``` ![自定义mask过渡背景色](images/alert006.jpg) ### 🔸 Toast 提示(自动关闭) ```javascript function toast1() { Swal.fire({ toast: true, title: '操作成功', icon: 'success', position: 'center', // 可选:让 Toast 居中显示 showConfirmButton: false, timer: 3000, timerProgressBar: true, didOpen: (toast) => { toast.onmouseenter = Swal.stopTimer; toast.onmouseleave = Swal.resumeTimer; } }) } ``` ![Toast 提示(自动关闭)](images/alert007.png) ### 🔸 使用自定义模板弹框(全屏)(点击:确认、取消、deny 按钮后回调的使用) #### 1. 放在HTML中模板代码 ```html ``` #### 2. 放在js中的调用代码 ```js function templateBtn() { Swal.fire({ grow: 'fullscreen', template: "#my-template" }).then((result) => { if (result.isConfirmed) { // 用户点击了“确认” Swal.fire('已删除!', '你的文件已被删除。', 'success'); } else if (result.dismiss === Swal.DismissReason.cancel) { Swal.fire('已取消', '你的文件是安全的。', 'info'); } else { Swal.fire('其他方式关闭(如', '你的文件是安全的。', 'info'); } }); } ``` ![使用自定义模板弹框(全屏)(点击:确认、取消、deny 按钮后回调的使用)](images/alert008-1.png) ![使用自定义模板弹框(全屏)(点击:确认、取消、deny 按钮后回调的使用)](images/alert008-2.png) ### 🔸 显示footer并添加链接 ```javascript Swal.fire({ icon: "error", title: "哎哟...", text: "出错了!", footer: '查看解决方法?' }); ``` ![显示footer并添加链接](images/alert009.png) ### 🔸 显示图片(imageHeight: 1500 可以显示滚动条) ```javascript Swal.fire({ imageUrl: "https://j.quhuichang.cn/AwsRCH250823/imagex/topBanner.jpg", imageHeight: 150, imageAlt: "A tall image" }); ``` ![显示图片(imageHeight: 1500 可以显示滚动条)](images/alert010.png) ### 🔸 可拖动的模态窗口(可以拖动到窗口任意位置) ```javascript Swal.fire({ title: "Drag me!", icon: "success", draggable: true }); ``` ### 🔸 自定义HTML描述和带有ARIA标签的按钮,autofocus获取焦点 ```javascript Swal.fire({ title: "HTML example", icon: "info", html: `You can use bold text, links, and other HTML tags`, showCloseButton: true, showCancelButton: true, focusConfirm: false, confirmButtonText: ` Great!`, confirmButtonAriaLabel: "Thumbs up, great!", cancelButtonText: ``, cancelButtonAriaLabel: "Thumbs down" }); ``` ![自定义HTML描述和带有ARIA标签的按钮,autofocus获取焦点](images/alert012.png) ### 🔸 有三个按钮及点击回调(confirm、Cancel、Deny) ```javascript Swal.fire({ title: "Do you want to save the changes?", showDenyButton: true, showCancelButton: true, confirmButtonText: "Save", denyButtonText: `Don't save` }).then((result) => { /* Read more about isConfirmed, isDenied below */ if (result.isConfirmed) { Swal.fire("Saved!", "", "success"); } else if (result.isDenied) { Swal.fire("Changes are not saved", "", "info"); } }); ``` ![有三个按钮及点击回调(confirm、Cancel、Deny)](images/alert013.png) ### 🔸 自定义定位对话框,3秒后自动关闭 ```javascript Swal.fire({ position: "top-end", icon: "success", title: "Your work has been saved", showConfirmButton: false, timer: 3000 }); ``` ![自定义定位对话框,3秒后自动关闭](images/alert014.png) ### 🔸 带有自定义图像的消息 ```javascript Swal.fire({ title: "Sweet!", text: "Modal with a custom image.", imageUrl: "https://unsplash.it/400/200", imageWidth: 400, imageHeight: 200, imageAlt: "Custom image" }); ``` ![带有自定义图像的消息](images/alert015.png) ### 🔸 自定义按钮CSS样式(点击:确认、取消 按钮后可以执行其它操作代码) #### 1. 自定义的CSS ```css .btn { display: inline-block; font-weight: normal; text-align: center; white-space: nowrap; vertical-align: middle; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; border: 1px solid transparent; margin: 0 0.5rem; padding: 0.5rem 0.75rem; font-size: 1rem; line-height: 1.25; border-radius: 0.25rem; transition: all 0.15s ease-in-out; } .btn:focus, .btn:hover { text-decoration: none; } .btn:focus, .btn.focus { outline: 0; box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25); } .btn.disabled, .btn:disabled { opacity: 0.65; } .btn:active, .btn.active { background-image: none; } a.btn.disabled, fieldset[disabled] a.btn { pointer-events: none; } .btn-success { color: #fff; background-color: #28a745; border-color: #28a745; } .btn-success:hover { color: #fff; background-color: #218838; border-color: #1e7e34; } .btn-success:focus, .btn-success.focus { box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.5); } .btn-success.disabled, .btn-success:disabled { background-color: #28a745; border-color: #28a745; } .btn-success:active, .btn-success.active, .show > .btn-success.dropdown-toggle { background-color: #218838; background-image: none; border-color: #1e7e34; } .btn-danger { color: #fff; background-color: #dc3545; border-color: #dc3545; } .btn-danger:hover { color: #fff; background-color: #c82333; border-color: #bd2130; } .btn-danger:focus, .btn-danger.focus { box-shadow: 0 0 0 3px rgba(220, 53, 69, 0.5); } .btn-danger.disabled, .btn-danger:disabled { background-color: #dc3545; border-color: #dc3545; } .btn-danger:active, .btn-danger.active, .show > .btn-danger.dropdown-toggle { background-color: #c82333; background-image: none; border-color: #bd2130; } ``` #### 2. JS代码 ```javascript const swalWithBootstrapButtons = Swal.mixin({ customClass: { confirmButton: "btn btn-success", cancelButton: "btn btn-danger" }, buttonsStyling: false }); swalWithBootstrapButtons.fire({ title: "Are you sure?", text: "You won't be able to revert this!", icon: "warning", showCancelButton: true, confirmButtonText: "Yes, delete it!", cancelButtonText: "No, cancel!", reverseButtons: true }).then((result) => { if (result.isConfirmed) { swalWithBootstrapButtons.fire({ title: "Deleted!", text: "Your file has been deleted.", icon: "success" }); } else if ( /* Read more about handling dismissals below */ result.dismiss === Swal.DismissReason.cancel ) { swalWithBootstrapButtons.fire({ title: "Cancelled", text: "Your imaginary file is safe :)", icon: "error" }); } }); ``` ![自定义按钮CSS样式](images/alert016.png) ### 🔸 带有自定义宽度、填充、背景 和动画gif的消息框 使用的两张图片放在images下的 trees.png 和 nyan-cat.gif ```javascript Swal.fire({ title: "Custom width, padding, color, background.", width: 600, padding: "3em", color: "#716add", background: "#fff url(https://sweetalert2.github.io/images/trees.png)", backdrop: ` rgba(0,0,123,0.4) url("https://sweetalert2.github.io/images/nyan-cat.gif") left top no-repeat ` }); ``` ![带有自定义宽度、填充、背景 和动画gif的消息框](images/alert017.png) ### 🔸 带有自动关闭定时器 ```javascript let timerInterval; Swal.fire({ title: "Auto close alert!", html: "I will close in milliseconds.", timer: 4000, timerProgressBar: true, didOpen: () => { Swal.showLoading(); const timer = Swal.getPopup().querySelector("b"); timerInterval = setInterval(() => { timer.textContent = `${Swal.getTimerLeft()}`; }, 100); }, willClose: () => { clearInterval(timerInterval); } }).then((result) => { /* Read more about handling dismissals below */ if (result.dismiss === Swal.DismissReason.timer) { console.log("I was closed by the timer"); } }); ``` ![带有自动关闭定时器](images/alert018.png) ### 🔸 从右向左支持阿拉伯语、波斯语、希伯来语和其他RTL语言 ```javascript Swal.fire({ title: "هل تريد الاستمرار؟", icon: "question", iconHtml: "؟", confirmButtonText: "نعم", cancelButtonText: "لا", showCancelButton: true, showCloseButton: true }); ``` ![带有自动关闭定时器](images/alert019.png) ### 🔸 AJAX请求示例,带有输入框,输入后检查github是否有用户主页 ```javascript Swal.fire({ title: "Submit your Github username", input: "text", inputAttributes: { autocapitalize: "off" }, showCancelButton: true, confirmButtonText: "Look up", showLoaderOnConfirm: true, preConfirm: async (login) => { try { const githubUrl = ` https://api.github.com/users/${login} `; const response = await fetch(githubUrl); if (!response.ok) { return Swal.showValidationMessage(` ${JSON.stringify(await response.json())} `); } return response.json(); } catch (error) { Swal.showValidationMessage(` Request failed: ${error} `); } }, allowOutsideClick: () => !Swal.isLoading() }).then((result) => { if (result.isConfirmed) { Swal.fire({ title: `${result.value.login}'s avatar`, imageUrl: result.value.avatar_url }); } }); ``` ![AJAX请求示例,带有输入框,输入后检查github是否有用户主页](images/alert020-1.jpg) ![AJAX请求示例,带有输入框,输入后检查github是否有用户主页](images/alert020-2.jpg) ![AJAX请求示例,带有输入框,输入后检查github是否有用户主页](images/alert020-3.jpg) ### 🔸 自定义ICON,自定义CSS使ICON一直旋转 #### 1 旋转的CSS ```css .rotate-y { animation: rotateY 1s infinite linear; } @keyframes rotateY { to { transform: rotateY(360deg); } } ``` #### 2 自定义ICON ```javascript const doubleCheckIcon = '' Swal.fire({ title: 'My Icon is Special!', icon: 'success', iconHtml: doubleCheckIcon, customClass: { icon: 'rotate-y', }, }) ``` ![自定义ICON,自定义CSS使ICON一直旋转](images/alert021.png) ## 其它说明 ### Icons success、 error、 warning、 info、 question ### 输入类型 text、 email、 url、 password、 textarea、 select、 radio、 checkbox、 date、 file、 range