到目前为止,我有这个代码,在5秒后将用户重定向到正确的URL:
<?php
$url = $_GET['url'];
header("refresh:5;url=$url");
include('ads.php');
?>
请你能告诉我怎样才能显示一个倒计时器,说明重定向... ...是剩下的秒数。我是网络开发的新手,所以所有代码都会有所帮助!
答案 0 :(得分:17)
<script type="text/javascript">
(function () {
var timeLeft = 5,
cinterval;
var timeDec = function (){
timeLeft--;
document.getElementById('countdown').innerHTML = timeLeft;
if(timeLeft === 0){
clearInterval(cinterval);
}
};
cinterval = setInterval(timeDec, 1000);
})();
</script>
Redirecting in <span id="countdown">5</span>.
你可以试试这个。
答案 1 :(得分:5)
因为这是一个常见的初学者问题;我只想强调,为了获得最佳实践setInterval
,通常可以通过在函数中递归使用setTimeout
来避免 。
例如:
var timer = 5,
el = document.getElementById('countdown');
(function t_minus() {
'use strict';
el.innerHTML = timer--;
if (timer >= 0) {
setTimeout(function () {
t_minus();
}, 1000);
} else {
// do stuff, countdown has finished.
}
}());
答案 2 :(得分:0)
凯尔的优秀代码。我用暂停和恢复按钮修改了计时器。
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var time_left = 50;
var cinterval;
var timestatus=1;
function time_dec(){
time_left--;
document.getElementById('countdown').innerHTML = time_left;
if(time_left == 0){
clearInterval(cinterval);
}
}
function resumetime()
{
//time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
function defaultstart()
{
time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
function stopstarttime()
{
if(timestatus==1)
{
clearInterval(cinterval);
document.getElementById('stopbutton').value="Start";
timestatus=0;
}
else
{
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
document.getElementById('stopbutton').value="Stop";
timestatus=1;
}
}
defaultstart();
</SCRIPT>
</HEAD>
<body>
Redirecting In <span id="countdown">50</span>.
<INPUT TYPE="button" value="stop" id="stopbutton" onclick="stopstarttime()">
</body>
</HTML>
答案 3 :(得分:0)
这是我对它的看法,没有函数之外的变量。取决于jQuery。
function count_down_to_action(seconds, do_action, elem_selector)
{
seconds = typeof seconds !== 'undefined' ? seconds : 10;
$(elem_selector).text(seconds)
var interval_id = setInterval(function(){
if (seconds <= 0)
{
clearInterval(interval_id);
if (typeof do_action === 'function')
do_action();
}
else
$(elem_selector).text(--seconds);
},1000)
}
的示例