我已使用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库中添加关闭按钮?

最佳答案

您可以定义一个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>

10-06 15:06