2017-05-11 186 views
1

我想这个默认秒计时器更改为秒倒计时,但它不工作一些如何的Javascript倒计时毛刺

这里是我试图编辑

https://codepen.io/martingrand/pen/pqxtc

这里脚本这是我做

https://codepen.io/anon/pen/mmXbZR

谁能告诉我我是什么脚本做错了?

我的jQuery

var sec = 155; 
calcValues(); 
var intvel = setInterval(calcValues, 1000); 

function calcValues() { 
    $('.counter .to') 
     .addClass('hide') 
     .removeClass('to') 
     .addClass('from') 
     .removeClass('hide') 
     .addClass('n') 
     .find('span:not(.shadow)').each(function (i, el) { 
     $(el).text(getSec(true)); 
    }); 
    $('.counter .from:not(.n)') 
     .addClass('hide') 
     .addClass('to') 
     .removeClass('from') 
     .removeClass('hide') 
    .find('span:not(.shadow)').each(function (i, el) { 
     $(el).text(getSec(false)); 
    }); 
    $('.counter .n').removeClass('n'); 
} 

function getSec(next) { 
    var d = new Date(); 
    if (next) { 
     sec--; 
     if (sec == 0) { 
      clearInterval(intvel); 
     } 
    } else if(sec == 60) { 
     sec = 0; 
    } 

    return (sec == 10 ? '0' + sec : sec); 
} 
+0

你要什么修改? – SjaakvBrabant

+0

你想在这里做什么?第一个代码笔确实在几秒钟内完成倒数计时 - 您想要更改什么? – Jaya

回答

0

这里的逻辑是错误的

return (sec == 10 ? '0' + sec : sec); 

你的意思是,如果秒等于10,不是增加一个零。它应该是如果少于10.

return (sec < 10 ? '0' + sec : sec); 

现在的问题,好像调用你的getSeconds两次是你的问题。所以,而不是调用它两次,做一次。

function calcValues() { 

    var secs = getSec(true); //store it 
    $('.counter .to') 
     .addClass('hide') 
     .removeClass('to') 
     .addClass('from') 
     .removeClass('hide') 
     .addClass('n') 
     .find('span:not(.shadow)').each(function (i, el) { 
     $(el).text(secs); //use it 
    }); 
    $('.counter .from:not(.n)') 
     .addClass('hide') 
     .addClass('to') 
     .removeClass('from') 
     .removeClass('hide') 
    .find('span:not(.shadow)').each(function (i, el) { 
     $(el).text(secs); //use it 
    }); 
    $('.counter .n').removeClass('n'); 
} 
0

问题是,您要全局定义sec变量。当调用秒(真)时,全局秒变量将减少1。然后,当您拨打秒(假)时,它会得到与您先前呼叫相同的结果。

这应该更好的工作:

var sec_counter = 10; 
calcValues(); 
var intvel = setInterval(calcValues, 1000); 
function calcValues() { 
    $('.counter .to') 
     .addClass('hide') 
     .removeClass('to') 
     .addClass('from') 
     .removeClass('hide') 
     .addClass('n') 
     .find('span:not(.shadow)').each(function (i, el) { 
     $(el).text(getSec(true)); 
    }); 
    $('.counter .from:not(.n)') 
     .addClass('hide') 
     .addClass('to') 
     .removeClass('from') 
     .removeClass('hide') 
    .find('span:not(.shadow)').each(function (i, el) { 
     $(el).text(getSec(false)); 
    }); 
    $('.counter .n').removeClass('n'); 
    sec_counter --; 
} 
function getSec(next) { 
    var sec = sec_counter; 
    if (next) { 

     if (sec == 0) { 
      clearInterval(intvel); 
     } 
     else{ 
      sec --; 
     } 
    } else if(sec == 60) { 
     sec = 0; 
    } 
    return (sec < 10 ? '0' + sec : sec); 
}