如何在SweetAlert中添加关闭按钮弹出

时间:2017-09-27 12:02:53

标签: javascript angularjs sweetalert sweetalert2

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

2 个答案:

答案 0 :(得分:4)

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。

答案 1 :(得分:2)

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