我的客户想要一个债务计数器显示每秒0.80美分的债务从2016年1月1日累计量上升。很显然,我不能有事情刷新页面加载和我到处找东西,会做到这一点。长话短说,我找不到我所寻找的,所以我想我可以发挥创意与下面的代码,使用反向倒计时计数器和可设置的数字等于债务正确的金额。
另外,我不是一个数学的人,所以答案可能会寻找我的脸。
以下是我现在使用(由罗伯特·哈什米安 - hashemian.com)的代码:
在我的index.html显示计数器:
<script language="JavaScript">
TargetDate = "01/01/2016 12:00 AM";
BackColor = "";
ForeColor = "white";
CountActive = true;
CountStepper = 1;
LeadingZero = true;
DisplayFormat = "$%%D%%,%%H%%,%%M%%,%%S%%";
FinishMessage = "It is finally here!";
</script>
JavaScript文件:
function calcage(secs, num1, num2) {
s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2)
s = "0" + s;
return "<b>" + s + "</b>";
}
function CountBack(secs) {
if (secs < 0) {
document.getElementById("cntdwn").innerHTML = FinishMessage;
return;
}
DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000));
DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));
DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));
DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));
document.getElementById("cntdwn").innerHTML = DisplayStr;
if (CountActive)
setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod);
}
function putspan(backcolor, forecolor) {
document.write("<span id='cntdwn' style='background-color:" + backcolor +
"; color:" + forecolor + "'></span>");
}
if (typeof(BackColor)=="undefined")
BackColor = "white";
if (typeof(ForeColor)=="undefined")
ForeColor= "black";
if (typeof(TargetDate)=="undefined")
TargetDate = "12/31/2020 5:00 AM";
if (typeof(DisplayFormat)=="undefined")
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
if (typeof(CountActive)=="undefined")
CountActive = true;
if (typeof(FinishMessage)=="undefined")
FinishMessage = "";
if (typeof(CountStepper)!="number")
CountStepper = -1;
if (typeof(LeadingZero)=="undefined")
LeadingZero = true;
CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0)
CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
putspan(BackColor, ForeColor);
var dthen = new Date(TargetDate);
var dnow = new Date();
if(CountStepper>0)
ddiff = new Date(dnow-dthen);
else
ddiff = new Date(dthen-dnow);
gsecs = Math.floor(ddiff.valueOf()/1000);
CountBack(gsecs);
我没有结婚到任何上述,如果有人有一个更好的代码或想法。由于任何人愿意帮助!
这应该让你开始。初次拿到那么当前余额更新它的每一秒使用的setInterval。您可以从setInterval函数内完成所有的渲染。
var date1 = new Date("01/01/2016 00:00:00");
var date2 = new Date();
var diff = (date2.getTime() - date1.getTime())/1000;
var debt = diff*.80
setInterval ( function() {
debt += .80;
console.log(debt.toFixed(2));
}, 1000);
或者是这样的
const date1 = new Date("01/01/2016 00:00:00");
setInterval ( function() {
var date2 = new Date();
var diff = (date2.getTime() - date1.getTime())/1000;
var debt = diff*.80
console.log(debt.toFixed(2));
}, 1000);