Sweetalert 延迟弹出窗口的打开

4

我试图延迟 SweetAlert 弹窗,在被触发后几秒钟内不显示。

例如,用户在网页上执行操作触发 SweetAlert,但它不是立即显示,而是等待 2 秒钟后再显示。我一直在研究各种方法来实现这个目标,但没有成功...我认为可能需要使用 setTimeout 函数?

这是我的 SweetAlert 函数,目前已经可以正常工作:

if( response == 10 ){
    swal({
      type: 'success',
      title: 'YOUR BALANCED BOX IS FULL',
      text: 'Youve added the recommended amount of items for your plan!',
      allowOutsideClick: false,
      showCancelButton: true,
      cancelButtonText: "Modify Selection",
      cancelButtonColor: '#d33',
      showConfirmButton: true,
      confirmButtonColor: '#61ce70',
      confirmButtonText: "Proceed To Cart",
    }).then((result) => {
        if (result.value) {
            window.location = "/basket/";
        }
    }) 
}

需要帮助!


这个会用 setTimeout 吗? - Adam H
2个回答

2

SweetAlert 2的具体解答:

Leo提供的代码逻辑解答是正确的。我分享了使用SweetAlert 2的最终版本,其中添加了setTimeout函数来延迟弹出窗口。

setTimeout函数包裹了整个SweetAlert 2函数,并且计时器在函数末尾设置(在本例中为3000)。

希望这能帮助任何想要做同样事情的人!

    setTimeout(function(){swal({
  type: 'success',
  title: 'YOUR BALANCED BOX IS FULL',
  text: 'Youve added the recommended amount of items for your plan!',
  allowOutsideClick: false,
  showCancelButton: true,
  cancelButtonText: "Modify Selection",
  cancelButtonColor: '#d33',
  showConfirmButton: true,
  confirmButtonColor: '#61ce70',
  confirmButtonText: "Proceed To Cart",
}).then((result) => {
  if (result.value) {
    window.location = "/basket/";
  }
})},3000); 

1

确实可以使用setTimeout轻松实现这一点,我设置了一个简单的代码片段,让您可以尝试一下!

// When button gets clicked.
$("#button").click(() => {
 // Instantely change it's text to loading..
 $("#button").text("Loading!");
  // Wait 2kms then change the text to Done!
 setTimeout(() => {
   $("#button").text("Done!");
  }, 2000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Event</button>

-Leo


1
谢谢Leo!帮我找到了答案。我已将你的回答标为正确,并在下面添加了具体解决方案。 - Giuls

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接