javascript代码,在页面实现倒计时,但不随页面刷新而刷新。

JavaScript09

javascript代码,在页面实现倒计时,但不随页面刷新而刷新。,第1张

实现倒计时很容易,关键是你要求刷新页面,不能停止倒计时

1、使用iframe,嵌入页面,父页上执行js操作,这样子页面刷新后会接着显示倒计时;

2、在后台实现,如使用java的timer类来实现倒计时,前台通过ajax获取倒计时结果,无论前端页面怎么刷新,不会停止倒计时

前端的好写,简单写下,仅供参考

<html>

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312" />

<title>无标题文档</title>

</head>

<body onLoad="startCount()" onUnload="fromClose()">

<iframe id="myFrame" src="innerPage.html" height="500" width="500"></iframe>

</body>

</html>

<script>

var timer

var count=10

function startCount(){

timer=window.setInterval("myTimeBack()",1000)

}

function myTimeBack(){

myFrame.document.getElementById("myInput").value=count

count=count-1

if(count==0)

count=10

}

function fromClose(){

clearInterval(timer)

}

</script>

//嵌入的页面innerPage.html

<html>

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312" />

<title>无标题文档</title>

</head>

<body>

<input type="text" value="" id="myInput" style="width:50">

<button onClick="refeshFrame()" style="width:80">refresh</button>

</body>

</html>

<script>

function refeshFrame(){

this.location.href=this.location.toString()

}

</script>

var timer = 60

var timerObj = setInterval(function(){

if(timer == 0){

alert('时间到了')

clearInterval(timerObj)

}

timer--

},1000)

这个是每一秒执行一次,你可以设置一个外部变量 设为倒计时的次数,每次执行的时候减一,当等于0,就说明时间到了