📅  最后修改于: 2023-12-03 14:47:47.335000             🧑  作者: Mango
SweetAlert 是一个漂亮且易于使用的弹出框插件,可以通过自定义按钮来实现交互。在某些情况下,我们可能需要关闭自定义按钮的单击事件,以便用户不能执行某些操作。在这篇文章中,我们将学习如何使用 SweetAlert 关闭自定义按钮的单击事件。
首先,我们需要在我们的 HTML 文件中引入 SweetAlert 插件。你可以通过 CDN 或下载它并将文件包含在你的项目中。以下是通过 CDN 引入 SweetAlert 的代码:
<script src="https://cdn.jsdelivr.net/npm/sweetalert@2"></script>
接下来,让我们创建一个 SweetAlert 弹出框。在本例中,我们将为用户提供两个自定义按钮。第一个按钮称为“确认”,第二个按钮称为“取消”:
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'Cancel'
}).then((result) => {
if (result.isConfirmed) {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
}
})
在这里,我们使用了 Swal.fire()
方法创建了一个弹出框。这个方法接收一个对象作为参数,其中包含了弹出框的标题、消息、图标和自定义按钮等内容。当用户单击其中一个按钮时,then()
方法会返回一个 result
对象,我们可以使用其中的属性来确定哪个按钮被单击。
现在,让我们来看看如何禁用自定义按钮的单击事件。为了实现这一点,我们将需要在“确认”按钮上添加一个禁止属性。在 Swal.fire()
中,我们可以使用 didClose
事件来监视弹出框关闭事件并将禁用属性从按钮中删除。这样,如果用户重新打开弹出框,他们将可以再次单击该按钮。
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'Cancel',
didClose: () => {
document.getElementById('confirmBtn').removeAttribute('disabled');
},
preConfirm: () => {
return new Promise((resolve) => {
document.getElementById('confirmBtn').setAttribute('disabled', true);
resolve();
})
}
}).then((result) => {
if (result.isConfirmed) {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
}
})
这里我们通过添加了一个 preConfirm
属性来捕获“确认”按钮的单击事件。在这个属性函数中,我们会将按钮禁用并使用一个 Promise 来等待弹出框关闭。一旦弹出框被关闭,我们在 didClose
事件中将禁用属性从按钮中删除,以便用户可以再次单击它。
SweetAlert 是一个非常有用的弹出框插件,可以帮助我们轻松地创建自定义交互。在本文中,我们学习了如何关闭自定义按钮的单击事件,以限制用户执行某些操作。禁用按钮是通过 preConfirm
和 didClose
事件实现的。您可以在此基础上构建自己的功能或使用案例。