【问题标题】:How do I create an animated number counter using Alpine.js?如何使用 Alpine.js 创建动画数字计数器?
【发布时间】:2020-12-18 05:27:05
【问题描述】:

我想使用 alpine js 创建一个动画数字计数器,如果有插件或者可以帮助我的东西,请告诉我。

代码:

<div id="counter">Counter: <b counter="0">0</b></div>

function update_users_count() {
    $('#counter b').animate({
        counter: 25000
    }, {
        duration: 6000,
        easing: 'swing',
        step: function(now) {
            $(this).text(Math.ceil(now));
        },
        complete: update_users_count
    });
};
update_users_count();

Alpine.JS

错误代码是:未捕获的 ReferenceError:未定义 counterA

<script>
function counterExample() {
    return {
        counterA: 0,
        target: '+100',
        time: 2000,
        init() {
            const start = counterA;
            const steps = time / (target - start);
            const handle = setInterval(() => {
                if (counterA < target) {
                    counterA += Math.round((target - start) / steps);
                } else {
                    clearInterval(handle);
                    counterA = target;
                }
            }, time / steps);
        }
    }
}
</script>

我想做的例子:

【问题讨论】:

    标签: javascript jquery animation alpine.js


    【解决方案1】:

    <!DOCTYPE html>
    <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js" defer></script><html>
    <body>
        <div x-data="{ current: 0, target: 1000, time: 300}" x-init="() => {
            start = current; 
            const interval = Math.max(time / (target - start), 5); 
            const step = (target - start) /  (time / interval);  
            const handle = setInterval(() => {
                if(current < target) 
                    current += step
                else {
                    clearInterval(handle);
                    current = target
                }   
                }, interval)
        }">
                 <div class="card"x-text="Math.round(current)">
        </div>
    </body>
    
    </html>

    【讨论】:

    • target选项中有一个简单的问题,当我将其更改为例如 1000 时,它太慢了
    • @jhon-jhonesi 做了一些微调。我测试了它。但你应该自己弄清楚。
    • 我自定义了代码,但它不起作用&lt;script&gt; function counterExample() { return { counterA: 0, target: '100', time: 2000, init() { start = counterA; const steps = time / (target - start); const handle = setInterval(() =&gt; { if(counterA &lt; target) { counterA += Math.round((target - start) / steps); } else { clearInterval(handle); counterA = target; } }, time/steps); } } } &lt;/script&gt;
    • target : '100' 你传递了字符串.... 并用这种格式完成你的评论....
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 2016-10-19
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多