Как мне сделать так, чтобы число на моей странице быстро подсчитывалось от 0 до 60 при загрузке?

Я представляю элемент стиля быстрого счетчика пробега, похожий по стилю на вращающиеся числа на этом веб-сайте (прокрутите вниз немного), но с числами, вращающимися от нуля до 60 или, возможно, от 0 до 100, сбрасываемыми обратно на 0, а затем до 60, и вращаются в том же направлении.

Вот изображение статической страницы для справки: http://d.pr/i/F1rc

введите здесь описание изображения

Это процент в середине, который я хочу анимировать при загрузке страницы.

Спасибо за любую помощь


person iminaii    schedule 29.11.2013    source источник
comment
Вы не можете сделать это с помощью анимации css.   -  person Tomáš Zato - Reinstate Monica    schedule 29.11.2013
comment
Согласен - вам понадобится javascript для этого...   -  person Pat Dobson    schedule 29.11.2013
comment
Дуп? Кто-то написал плагин Javascript для подсчета до определенного числа за определенное время (мс) - stackoverflow.com/a/2540673/ 2470724   -  person Nick R    schedule 29.11.2013
comment
Мало того, что он задает глупые вопросы. Он даже не читал ответы.   -  person Tomáš Zato - Reinstate Monica    schedule 01.12.2013


Ответы (4)


Вы можете сделать это исключительно в CSS и HTML, однако это определенно неразумный выбор, использование JS будет работать лучше и эффективнее.

Пример FIDDLE

ul,
li {
  list-style: none;
  margin: 0;
  padding: 0;
}
.circle {
  background: red;
  border-radius: 999px;
  display: inline-block;
  height: 150px;
  padding: 100px 0 0 20px;
  width: 230px;
  color: white;
  font-size: 50px;
  font-family: verdana;
  font-weight: bold;
}
.counter {
  height: 50px;
  overflow: hidden;
  position: relative;
  display: inline-block;
  text-align: center;
}
ul {
  -webkit-animation: counter 4s infinite;
  -moz-animation: counter 4s infinite;
  animation: counter 4s infinite;
  position: relative;
}
@-webkit-keyframes counter {
  0% {
    top: 0;
  }
  10% {
    top: -50px;
  }
  20% {
    top: -100px;
  }
  30% {
    top: -150px;
  }
  40% {
    top: -200px;
  }
  50% {
    top: -250px;
  }
  60% {
    top: -300px;
  }
  70% {
    top: -350px;
  }
  80% {
    top: -400px;
  }
  90% {
    top: -450px;
  }
  100% {
    top: 0px;
  }
}
@-moz-keyframes counter {
  0% {
    top: 0;
  }
  10% {
    top: -50px;
  }
  20% {
    top: -100px;
  }
  30% {
    top: -150px;
  }
  40% {
    top: -200px;
  }
  50% {
    top: -250px;
  }
  60% {
    top: -300px;
  }
  70% {
    top: -350px;
  }
  80% {
    top: -400px;
  }
  90% {
    top: -450px;
  }
  100% {
    top: 0px;
  }
}
@keyframes counter {
  0% {
    top: 0;
  }
  10% {
    top: -50px;
  }
  20% {
    top: -100px;
  }
  30% {
    top: -150px;
  }
  40% {
    top: -200px;
  }
  50% {
    top: -250px;
  }
  60% {
    top: -300px;
  }
  70% {
    top: -350px;
  }
  80% {
    top: -400px;
  }
  90% {
    top: -450px;
  }
  100% {
    top: 0px;
  }
}
<div class='circle'>
  +
  <div class='counter'>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
      <li>6</li>
      <li>7</li>
      <li>8</li>
      <li>9</li>
      <li>10</li>
    </ul>
  </div>%
</div>

person SW4    schedule 29.11.2013
comment
Не могли бы вы сделать его совместимым с Firefox? Мне довольно любопытно :) - person Tomáš Zato - Reinstate Monica; 29.11.2013
comment
Готово... теперь должно работать :) Вам нужно будет изменить скорость/числа и т. д. по мере необходимости. - person SW4; 29.11.2013
comment
Это вообще офигенно :D - person Tomáš Zato - Reinstate Monica; 29.11.2013
comment
Но я тоже сделал свой ответ безумным: P - person Tomáš Zato - Reinstate Monica; 29.11.2013

Возможно, вы захотите использовать JavaScript setTimeout.

Пусть следующее будет вашим числовым контейнером:

<div id="number"></div>

Дикий псевдокласс:

//Some iterator pseudo-class
function NumberIterator() {
    //The number to start with
    this.number = 0;
    //List of numbers to pass through
    this.goals = [];
    //Private - current goal
    var currentGoal = 0;
    //Whether to infinitelly loop around
    this.infinite = false;
    //Pause between changing number
    this.delay = 50;

    //Timeout ID 
    var t_id = null;
    //Self-reference
    var _this = this;
    //Is running or not
    var running = false;

    //This method will be called automatically
    this.step = function() {
        //If out goal is smaller than number decrease it
        if(this.number>this.goals[currentGoal])
          this.number--;
        //if our goal is larger, increase
        else if(this.number<this.goals[currentGoal])
          this.number++;
        //If equals, perform ongoal actions
        else {
          currentGoal++;
          if(currentGoal>=this.goals.length) {
              if(this.infinite)
                 currentGoal = 0;
              else {
                  this.stop();
              }
              if(typeof this.ongoal == "function")
                 this.ongoal(this.number);
          }
        }



        if(typeof this.onstep == "function")
            this.onstep(this.number);

        if(running) {
            tick();
        }

    }
    this.stop = function() {
        if(t_id!=null) {
            clearTimeout(t_id);
            t_id = null;
        }
        running = false;
    }

    //Start counter with this:
    this.start = function() {
        this.stop();
        running = true;
        this.step();
    }
    //This one is heart of the program. It delays between iterations
    function tick() {
        if(t_id!=null) {
            clearTimeout(t_id);
            t_id = null;
        }
        if(running)
          t_id = setTimeout(function() {_this.step();}, _this.delay);
    }
}

Применение:

//Save div element reference (it's faster to use reference than function call)
var div = document.getElementById("number");

//Set up ne instance of that class
var iterator = new NumberIterator();
//Configure waypoints
iterator.goals = [100,60,0,60];
//Set it to iterate indefinitely through waypoins (that's quite fun)
iterator.infinite = true;
//On step callback
iterator.onstep = function(num) {
    div.innerHTML = num;
}
//Start the thingy
iterator.start();

ПРИМЕР на jsfiddle

Если числовая анимация должна быть статической во времени, вы также можете использовать анимацию GIF (это также могут быть одноразовые анимации). Итак, если вы хотите, чтобы всегда было одно и то же, выберите свой любимый GIF-аниматор и создайте его как изображение. Он должен кэшироваться на стороне клиента.

person Tomáš Zato - Reinstate Monica    schedule 29.11.2013

Как насчет плагина:

$.fn.count = function(speed) {
    return this.each(function(_, elem) {
        var from = parseInt($(elem).data('from') || 0, 10),
            to   = parseInt($(elem).data('to') || 100, 10);

        $(elem).text(from);

        (function run(from, to) {
            $(elem).text(parseInt(from, 10)+1);
            if (from < to-1) setTimeout(function() {run(++from, to)}, speed || 300)
        })(from, to);
    });
}

который можно легко использовать как

$(element).count(100);

и где бы вы установили значения как

<div data-from="0" data-to="100">0</div>

FIDDLE

person adeneo    schedule 29.11.2013

 $(function() {
        function count($this){
            var current = parseInt($this.html(), 10);
            $this.html(++current);
            if(current !== $this.data('count')){
                setTimeout(function(){count($this)}, 50);
            }
        }        
      $("span").each(function() {
          $(this).data('count', parseInt($(this).html(), 10));
          $(this).html('0');
          count($(this));
      });
    });

http://jsfiddle.net/WpJxn/1/

person Muhammad Tahir    schedule 13.05.2015