Анимированный числовой счетчик jQuery от нуля до значения - счетчик показывает неправильное значение, когда значение составляет сотни тысяч

Я попытался анимировать числа с помощью этого URL-адреса: числовой счетчик от нуля до значения и следовал этому коду:

$('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 3000,
        easing: 'swing',
        step: function (now) {
          $(this).text(Math.ceil(now));
        }
    });
});

Проблема в том, что я дал число 800 000 для увеличения числового счетчика. Случайным образом это значение увеличивается и снова уменьшается до 0. Например. После увеличения значения до 800 000 анимация снова возвращается к значению 0.

Счетчик от нуля до значения работает нормально для меньших значений в тысячах.


person Prasanth Mahendiran    schedule 15.10.2019    source источник


Ответы (2)


Исследуя, как это сделать, я понял, что все решения в стеке основаны на jquery. Сейчас пишу натив (vanillajs) в проектах, мое решение таково.

var getCountItems = document.querySelectorAll('.count-item');
if(getCountItems){
    getCountItems.forEach(function (countItem) {
        var counterValueElement = countItem.querySelector('strong');
        var storeCurrentValue = parseInt(counterValueElement.textContent);

        var fromZero = 0;

        if(fromZero === 0){
            counterValueElement.textContent = "0";
        }

        setInterval(function () {
            if(++fromZero <= storeCurrentValue){
                counterValueElement.textContent = fromZero.toString();
            }
        }, 15); // set your speed (decrease)
    });
}
section#countdown{
    margin: 50px 0;
    width: 100%;
    color: #1C1E23;
}

section#countdown h3{
    font-size: 28px;
    text-align: center;
    position: relative;
    padding-bottom: 20px;
}

section#countdown h3:after{
    content: ' ';
    position: absolute;
    bottom: 0;
    left: 10%;
    height: 1px;
    width: 80%;
    background: rgba(28, 30, 35, 0.44);
}

section#countdown .count-item{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    font-size: 24px;
    color: rgba(28, 30, 35, 0.7);
    margin: 15px 0;
    /* set your anim count text for "all" */
    transition: all .3s ease, color .4s ease-in;
}

section#countdown .count-item:hover{
    transform: scale(1.25);
    color: #C22429;
}

section#countdown .count-item span{
    font-size: 18px;
    color: rgba(28, 30, 35, 0.44);
}

@media only screen and (max-width: 992px){
    section#countdown h3 + div{
        flex-direction: column;
    }

    section#countdown .count-item{
        transform: scale(1.5);
        margin: 30px 0;
    }
}
<section id="countdown" class="box-p">
    <h3>STATISTICS</h3>
    <div class="d-flex align-items-center justify-content-around">
        <div class="count-item">
            <strong>47</strong>
            <span>YEAR EXPERIENCE</span>
        </div>
        <div class="count-item">
            <strong>100</strong>
            <span>EXPORT COUNTRIES</span>
        </div>
        <div class="count-item">
            <strong>200</strong>
            <span>BRANDS</span>
        </div>
        <div class="count-item">
            <strong>500</strong>
            <span>EMPLOYEE</span>
        </div>
        <div class="count-item">
            <strong>7</strong>
            <span>SUB BRANDS</span>
        </div>
        <div class="count-item">
            <strong>2</strong>
            <span>FACTORY</span>
        </div>
    </div>
</section>

person Fatih Mert Doğancan    schedule 31.08.2020

Что-то вроде этого должно помочь,

$('.count').each(function() {
  $(this).prop('Counter', 8000)
    .animate({
      Counter: $(this).text()
    }, {
      duration: 3000,
      easing: 'swing',
      step: function(now, a) {
        $(this).text(8000 - ~~this.Counter);
      }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class='count'>0</span>

Надеюсь это поможет,

person Miroslav Glamuzina    schedule 15.10.2019
comment
$('.count').each(function () { $(this).prop('Counter', 0).animate({ Counter: $(this).data('value') }, { продолжительность: 3000 , easing: 'swing', step: function (now) { $(this).text(Math.ceil(now)); } }); }); На самом деле это отлично работает для меня. Я использовал значение данных, чтобы исправить это. - person Prasanth Mahendiran; 21.10.2019
comment
Спасибо за ответ Мирослава Гламузина. - person Prasanth Mahendiran; 21.10.2019