我想在5秒后使用SweetAlert2做一个可取消的自动关闭模式,但是我找不到停止计时器的方法,请帮忙!这是js代码:
$(document).on('click', '#view_more_trigger', function(e) {
e.preventDefault();
var div = document.getElementById('view_more');
div.style.display = div.style.display == 'none' ? 'block' : 'none';
$(this).html( div.style.display == 'none' ? "View Moar" : "View Less");
});
var closeInSeconds=10,
timerInterval;
var my_swal = swal({
type: 'success',
html: '<div id="view_more" style="display: none;">'+
$('#details').html() +
'</div>'+
'<a href="javascript:;" id="view_more_trigger" >View more</a>'+
'<p id="show_timeout" style="display: none;"></p>',
timer: closeInSeconds * 1000,
onOpen: () => {
$('#show_timeout').show();
timerInterval = setInterval(function() {
$(document).on('click', '#view_more_trigger', function(e) {
e.preventDefault();
console.log('trying desperately to cancel the damn timer!');
//swal.stop(); // error, function !exists
//my_swal.timeout.stop(); // Cannot read property 'stop' of undefined
//my_swal.timer.stop(); // Cannot read property 'stop' of undefined
// ..or to increase it
if(closeInSeconds<1000) {
console.log('incrementing closeInSeconds by 1000');
closeInSeconds +=1000;
}
//swal.timer = closeInSeconds * 1000;
swal.timer = closeInSeconds * 1000;
my_swal.timer = closeInSeconds * 1000;
clearInterval(timerInterval);
});
closeInSeconds--;
if (closeInSeconds < 0) {
clearInterval(timerInterval);
}
swal.getContent().querySelector('#show_timeout').textContent = (Math.round(swal.getTimerLeft()/1000)*1000)/1000 + 's';
}, 1000);
},
onClose: () => {
clearInterval(timerInterval)
},
showConfirmButton: false,
});
我发现与计时器一起使用的唯一功能是Swal.getTimerLeft()。
我在https://codepen.io/teoui/pen/MzdzWy中创建了一支笔,可以与
谢谢!
最佳答案
我是SweetAlert2的作者,刚刚发布了具有Swal.stopTimer()
支持的新版本。
使用方法如下:
Swal({
title: 'Auto close alert!',
html: 'I will close in 5 seconds. <a href id="stop-timer">Stop timer</a>',
timer: 5000,
onOpen: () => {
Swal.getContent().querySelector('#stop-timer').addEventListener('click', e => {
e.preventDefault()
Swal.stopTimer()
})
}
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@7"></script>
关于javascript - sweetalert2取消计时器/超时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53622723/