要实现一个标签或者按钮进行5秒到计时,非常简单,直接上代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 |
倒计时:<span id="timeSpan1"
style="color:red;font-size:20px">5</span>秒倒计时:<span id="timeSpan2"
style="color:red;font-size:20px">5</span>秒<script src="~/Scripts/jquery-1.8.2.min.js"></script><script>$(function
() {// setInterval 方法,需要给传当前的计时器变量,执行一次便可以自动重复执行,除非手动停止。var
timer = setInterval(function
() {_testBysetInterval(timer)}, 1000);//setTimeout 方法,只执行一次,需要反复调用。setTimeout(_testBysetTimeout , 1000);})function
_testBysetInterval(timer) {var
$timeSpan = $("#timeSpan1");time = parseInt($timeSpan.text());time--;if
(time <= 0) {$timeSpan.css("color", "gray")clearInterval(timer);//需要清除计时器}else
{$timeSpan.text(time);}}function
_testBysetTimeout() {var
$timeSpan = $("#timeSpan2");var
time = $timeSpan.text();time = parseInt(time);time--;//如果到0的话 就停止计时,并且改变颜色if
(time <= 0) { $timeSpan.css("color", "gray");}else
{$timeSpan.text(time);setTimeout(_testBysetTimeout, 1000) //需要重复调用}}</script> |
到此,用两种方法实现了同样的效果。两种方法对比,setInterval 更适合当前的场景。
Jquery实现简单到计时功能(setTimeout,setInterval),布布扣,bubuko.com
Jquery实现简单到计时功能(setTimeout,setInterval)
原文:http://www.cnblogs.com/lpfsky/p/3629689.html