4

我使用 SweetAlert 库在我的应用程序中显示一个弹出窗口。这是我的代码

swal({
    title: "Are you sure?",
    text: "Test message?",
    type: "info",
    showCancelButton: true,
    focusConfirm: false,
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes",
    cancelButtonText: "No"
}, function (isConfirm) {})

我需要在右上角添加一个关闭按钮。根据文档,关闭按钮仅适用于 SweetAlert2 库。

是否可以在 SweetAlert1 库中添加关闭按钮?

4

2 回答 2

8

您可以定义一个mySwal检查showCloseButton参数的包装器。

这是原始 SweetAlert 库的 v2.1.0 的示例:

mySwal = function() {
  swal(arguments[0]);
  if (arguments[0].showCloseButton) {
    closeButton = document.createElement('button');
    closeButton.className = 'swal2-close';
    closeButton.onclick = function() { swal.close(); };
    closeButton.textContent = '×';
    modal = document.querySelector('.swal-modal');
    modal.appendChild(closeButton);
  }
}

mySwal({
  title: "Are you sure?",
  text: "Test message?",
  icon: "info", /* type: "info", */
  buttons: [
    "No", /* showCancelButton: true, cancelButtonText: "No", */
    "Yes" /* confirmButtonText: "Yes", */
  ],
  focusConfirm: false,
  showCloseButton: true
});
.swal-button--confirm {
  background-color: #dd6b55; /* confirmButtonColor: "#DD6B55", */
}

.swal-modal .swal2-close {
  position: absolute;
  top: 0;
  right: 0;
  width: 1.2em;
  height: 1.2em;
  transition: color 0.1s ease-out;
  border: none;
  background: transparent;
  color: #cccccc;
  font-family: serif;
  font-size: 40px;
  cursor: pointer;
}

.swal-modal .swal2-close:hover {
  color: #f27474;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"></script>

于 2018-05-04T17:30:02.213 回答
8
swal({
title: "Are you sure?",
text: "Test message?",
type: "info",
showCancelButton: true,
focusConfirm: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
showCloseButton: true,

只需添加showCloseButton: true,这将在弹出窗口的右上角显示关闭 X 图标。

来源:参见SweetAlerts2 Docs上的“自定义 HTML 描述和带有 ARIA 标签的按钮”示例

请注意,它在现已弃用的 SweetAlert1 库中不可用,我建议使用 SweetAlert2。

于 2017-09-29T16:06:29.970 回答