jquery如何实现倒计时效果

来源:互联网 发布:淘宝自行车用品店推荐 编辑:程序博客网 时间:2024/05/29 18:28

首先获取当前时间与目标时间的时间差,然后通过定时器更新这个时间差,就实现了倒计时效果。实现上述过程需要以下两个函数:

1
2
getTime()       // 返回距1970年1月1日之间的毫秒数,这样将时间差(毫秒数)÷3600÷24即为天数,时分秒类似
setTimeout(code,millisec);    // 在指定的毫秒数后调用函数

实例演示如下

  1. 创建Html元素

    1
    2
    3
    4
    5
    6
    <div class="box">
        <span>距离2015年国庆节还剩:</span>
        <div class="content">
            <input type="text" id="time_d">天<input type="text" id="time_h">时<input type="text" id="time_m">分<input type="text" id="time_s">秒
        </div>
    </div>
  2. 设置css样式

    1
    2
    3
    4
    div.box{width:300px;padding:20px;margin:20px;border:4px dashed #ccc;}
    div.box>span{color:#999;font-style:italic;}
    div.content{width:250px;margin:10px 0;padding:20px;border:2px solid #ff6666;}
    input[type='text']{width:45px;height:35px;padding:5px 10px;margin:5px 0;border:1px solid #ff9966;}
  3. 编写jquery代码

    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
    $(function(){ 
        show_time();
    }); 
     
    function show_time(){ 
        var time_start = new Date().getTime(); //设定当前时间
        var time_end =  new Date("2015/10/01 00:00:00").getTime(); //设定目标时间
        // 计算时间差 
        var time_distance = time_end - time_start; 
        // 天
        var int_day = Math.floor(time_distance/86400000) 
        time_distance -= int_day * 86400000; 
        // 时
        var int_hour = Math.floor(time_distance/3600000) 
        time_distance -= int_hour * 3600000; 
        // 分
        var int_minute = Math.floor(time_distance/60000) 
        time_distance -= int_minute * 60000; 
        // 秒 
        var int_second = Math.floor(time_distance/1000) 
        // 时分秒为单数时、前面加零 
        if(int_day < 10){ 
            int_day = "0" + int_day; 
        
        if(int_hour < 10){ 
            int_hour = "0" + int_hour; 
        
        if(int_minute < 10){ 
            int_minute = "0" + int_minute; 
        
        if(int_second < 10){
            int_second = "0" + int_second; 
        
        // 显示时间 
        $("#time_d").val(int_day); 
        $("#time_h").val(int_hour); 
        $("#time_m").val(int_minute); 
        $("#time_s").val(int_second); 
        // 设置定时器
        setTimeout("show_time()",1000); 
    }
0 0
原创粉丝点击