jQuery or Javascript continuous counter (countup)

北慕城南 提交于 2019-12-01 14:41:36

If you want a javascript only solution, you can just make a div like this:

<div id="counter"></div>

And then use the following script somewhere on the page:

var START_DATE = new Date("July 27, 2010 13:30:00"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 2; // increase per tick
var START_VALUE = 9001; // initial value when it's the start date
var count = 0;

window.onload = function()
{
 var msInterval = INTERVAL * 1000;
 var now = new Date();
 count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
 document.getElementById('counter').innerHTML = count;
 setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = count;", msInterval);
}

You can use a technique similar to that of thenduks to get images, or you could just style the counter div with CSS.

Maybe you have a page with this markup:

<div id='counter'><%= some_number_from_database_or_similar() %></div>

And so you could write a script like this:

var INTERVAL = 1;

$(document).ready( function() {
  var delay = INTERVAL * 1000;
  var target = $('#counter');
  var counter = parseInt( target.text(), 10 );
  setInterval( function() {
    target.text( counter++ );
  }, delay );
} );

This isn't entirely accurate since you can't be sure the function will get called exactly once every second, but it'll be pretty close (and how accurate do you really need it to be, anyway?). Alternatively you could create a new Date() and get it's timestamp, then create another one every interval and just calculate the number of actual seconds that have passed... Seems too expensive to be worth it.

As far as using images for the numbers, you could just change the interval function to be something like:

function() {
  var counterString = (counter++).toString();
  var chunks = [];
  for( var i = 0; i < counterString.length; i++ ) {
    chunks.push( "<img src='/images/numbers/" + counterString[i] + ".png' />" );
  }
  target.html( chunks.join('') );
}

you can build it on your own or just use this plugin. there's a countup there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!