我有这个代码来完成这个任务:如果用户(mousemove 和 keypress)没有事件 10 秒然后显示一个对话框(Jquery UI 对话框)来警告并让用户知道他们将在下一个页面被重定向到另一个页面5 秒,除非他们做某事。如何使“您将在 5 秒后自动重定向到...”中的“5”倒数为 5、4、3、2、1 => 然后重定向?
<script>
// Set timeout variables.
var timoutWarning = 10000; // Display warning in 10 seconds.
var timoutNow = 15000; // Timeout in 15 seconds
var logoutUrl = 'http://google.com'; // URL to redirect to.
var warningTimer;
var timeoutTimer;
// Start timers.
function StartTimers() {
warningTimer = setTimeout("IdleWarning()", timoutWarning);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
}
// Reset timers.
function ResetTimers() {
clearTimeout(warningTimer);
clearTimeout(timeoutTimer);
StartTimers();
$("#timeout").dialog('close');
}
// Show idle timeout warning dialog.
function IdleWarning() {
$("#timeout").dialog({
modal: true
});
}
// redirect the user.
function IdleTimeout() {
window.location = logoutUrl;
}
</script>
html
<style>
#timeout {
display: none;
}
</style>
<body onload="StartTimers();" onmousemove="ResetTimers();" onclick="ResetTimers();">
<form id="form1" runat="server" defaultbutton="DoNothing">
<asp:Button ID="DoNothing" runat="server" Enabled="false" Style="display: none;" />
<div class="page-container">
<div class="container">
Hold your mouse and don't press any key for 10 seconds, an dialog alert will be displayed.
<div id="timeout">
<h1>Session About To Timeout</h1>
<p>
You will be automatically redirected to google after 5 seconds.<br />
To stay on this page move your mouse or press any key.
</p>
</div>
</div>
</div>
</form>
最佳答案
Vano 关于 jQuery 插件的建议很好,没有理由不使用它。不过,如果您想自己做,代码应该非常简单:
var timer = -1; //so the timer doesn't start until everything is rendered
setInterval(function() {
timer--;
if (!timer) {
window.location = logoutUrl;
} else if (timer <= 5) {
$('#timeout').html("Redirecting in " + timer + " seconds");
}
}, 1000);
$(document).on('ready keypress mousemove focus click scroll', function() {
timer = 15;
});
关于javascript - 如何让数字每秒倒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29775527/