在练习中,我们常常遇到一种问题就是,怎么实现页面N秒之后自动跳转呢?
这个是写在js代码里面的;
setTimeout
我自己遇到问题和查找资料,总结了3个方法
方法1:
最简单的一种:直接在前面<head>里面添加代码:
- <span style="font-size:18px;"> </span><span style="font-size:24px;"><meta http-equiv="refresh" content="3;URL=res.html"> </span>
- <span style="font-size:24px;">//3秒之后自动跳转到res.html,两个属于同一文件下面,要是需要跳转到jsp页面,就需要在url里面填写url地址————(浏览器的地址栏里面写入的数据,如:http://localhost:8080/TestDemo/1.jsp)</span>
方法2:
需要用到window里面的方法:
setTimeout | 经过指定毫秒值后计算一个表达式。 |
例子:
- window.setTimeout("alert('Hello, world')", 1000);
具体实现如下:
- <script type="text/javascript">
- onload=function(){ <span style="white-space:pre"> </span>//在进入网页的时候加载该方法
- setTimeout(go, 3000); <span style="white-space:pre"> </span> /*在js中是ms的单位*/
- };
- function go(){
- location.href="http://localhost:8080/TestDemo/index.jsp";
- }
- </script>
- //3秒之后自动执行go方法,直接跳转到index.jsp页面
方法3:
上面两个例子的缺陷就是能够实现跳转,但是不知道是什么时候跳转.实现倒数3-2-1;
settimeout方法已经做不了了;
setInterval | 每经过指定毫秒值后计算一个表达式。 |
没过相同的时间,就会执行相应的函数。具体的实现方法:
- <script type="text/javascript">
- onload=function(){
- setInterval(go, 1000);
- };
- var x=3; //利用了全局变量来执行
- function go(){
- x--;
- if(x>0){
- document.getElementById("sp").innerHTML=x; //每次设置的x的值都不一样了。
- }else{
- location.href='res.html';
- }
- }
- </script>