在js中實現頁面定時跳轉我們要使用setInterval或setTimeOut函數,當然還可以使用頁面的metea實現了,下面我介紹兩個實例。
例1
倒計時刷新頁面
代碼如下
<script type="text/javascript" language="JavaScript">
var startTime = new Date();
var endTime=startTime.getTime()+10*60*1000;
var g_blinkswitch = 0;
var g_blinktitle = document.title;
function getRemainTime(){
var nowTime = new Date();
var nMS =endTime - nowTime.getTime();
var nM=Math.floor(nMS/(1000*60)) % 60;
var nS=Math.floor(nMS/1000) % 60;
if(nM==0&&nS==0&&nMS<1000) //當倒計時結束
{
window.focus();
setInterval("blinkNewMsg()", 1000);
window.location.reload();
}
if(nS < 10) nS = "0" + nS;
if(nMS >= 0){
document.getElementById("remainTime").innerHTML= nM + "分" + nS + "秒";
setTimeout("getRemainTime()",1000);
}
}
function blinkNewMsg()
{
document.title = g_blinkswitch % 2==0 ? "【 】 - " + g_blinktitle : "【新消息】 - " +
g_blinktitle;
g_blinkswitch++;
}
window.onload=getRemainTime;
</script>
<strong id="remainTime">10分00秒</strong>
例2
倒計時跳轉頁面
代碼如下
<title>JS倒計時網頁自動跳轉代碼</title>
<script language="JavaScript" type="text/javascript">
function delayURL(url) {
var delay = document.getElementById("time").innerHTML;
if(delay > 0) {
delay--;
document.getElementById("time").innerHTML = delay;
} else {
window.top.location.href = url;
}
setTimeout("delayURL('" + url + "')", 1000);
}
</script>
<span id="time" style="background: #00BFFF">3</span>秒鐘後自動跳轉,如果不跳轉,請點擊下面的鏈接<a href="http://www.45it.com">我的百度</a>
<script type="text/javascript">
delayURL("http://www.45it.com");
</script>
防刷新的倒計時代碼
代碼如下
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title> www.45it.com</title>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
<!--
var maxtime;
if(window.name==''){
maxtime = 1*60;
}else{
maxtime = window.name;
}
function CountDown(){
if(maxtime>=0){
minutes = Math.floor(maxtime/60);
seconds = Math.floor(maxtime%60);
msg = "距離考試結束還有"+minutes+"分"+seconds+"秒";
document.all["timer"].innerHTML = msg;
if(maxtime == 5*60) alert('注意,還有5分鐘!');
--maxtime;
window.name = maxtime;
}
else{
clearInterval(timer);
alert("考試時間到,結束!");
}
}
timer = setInterval("CountDown()",1000);
//-->
</SCRIPT>
<div id="timer" style="color:red"></div>
</body>
</html>