jquery定时器,倒计时封装

引入jQuery,传入一个父级元素的id和一个时间就能多次调用,看完点赞哦,本人的第一篇博客。

jquery定时器,倒计时封装_第1张图片

css代码:

.countdown {
  height: 46px;
 background: #f73e2b;
}
.countdown p {
  color: #fff;
  font-size: 16px;
  text-align: center;
  line-height: 46px;
  word-spacing: 16px;
  font-weight: 400;
}

body:

<body>
        <div id="th1" class="countdown">
            <p>还剩下<span class="t_d">span><span class="t_h">span><span class="t_m">span><span class="t_s">span>结束,抓紧时间砍价吧!p>
        div>
        <div id="th2" class="countdown">
            <p>还剩下<span class="t_d">span><span class="t_h">span><span class="t_m">span><span class="t_s">span>结束,抓紧时间砍价吧!p>
        div>
    body>

js:

//倒计时

//调用时直接传入一个id和一个结束时间
addtime("th1","2018-05-28 10:40:00");

addtime("th2","2019-05-28 10:40:00");

function addtime(ids,time){
var timer = null;
for(var a=0;a window[arguments[a]] = time;
if(a<1){
function runtime(){
getRTime(window[arguments[a]],ids);
}
getRTime(window[arguments[a]],ids);
timer = setInterval(runrun,1000);
}
}
function runrun(){
clearInterval(timer);
addtime(ids,time);
}
}
function getRTime(endtime,id){
var EndTime = new Date(endtime.replace(/-/g,'/')).getTime();
var NowTime = new Date();
var t =EndTime - NowTime.getTime();
var this_d =id;
// console.log(t)
//如果日期是过去的时间点,t就是负*-1就相当于秒表计时
if(t<0){//时间结束后执行的方法
t*=-1;//倒计时变为正计时
}else{
var d=Math.floor(t/1000/60/60/24);
var h=Math.floor(t/1000/60/60%24);
var m=Math.floor(t/1000/60%60);
var s=Math.floor(t/1000%60);
if(h<10){
if(h == 0){
h = "0" + h;
}else{
h = "0" + h;
}
}
if(m<10){
if(m == 0){
m = "0" + m;
}else{
m = "0" + m;
}
}
if(s<10){
if(s == 0){
s = "0" + s;
}else{
s = "0" + s;
}
}
$('#'+this_d).find(".t_d")[0].innerHTML = d + "天"; //天
$('#'+this_d).find(".t_h")[0].innerHTML = h + "时"; //时
$('#'+this_d).find(".t_m")[0].innerHTML = m + "分"; //分
$('#'+this_d).find(".t_s")[0].innerHTML = s + "秒"; //秒
}
}

 

转载于:https://www.cnblogs.com/weibingchao/p/8966351.html

你可能感兴趣的:(javascript,runtime)