jquery 如何使用Alpine.js创建一个动画计数器?

xmjla07d  于 2023-08-04  发布在  jQuery
关注(0)|答案(2)|浏览(136)

我想创建一个动画计数器使用高山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();

字符串

阿尔卑斯山.JS

错误代码为:未捕获的引用错误: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>

我想做的示例:


的数据

n6lpvg4x

n6lpvg4x1#

<!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>

字符串

ivqmmu1c

ivqmmu1c2#

下面是我使用Alpine.js Intersect pluginrequestAnimationFrame的解决方案。分享给任何可能遇到这个问题的人!

<div x-data="{ visible: false, start: 0, target: 1000, duration: 3000 }"
    x-intersect:enter.full="visible = true" x-intersect:leave="visible = false; start = 0"
    x-init="$watch('visible', value => {
        const $el = $refs.el;
        const step = (timestamp) => {
            if (!start) start = timestamp;
            const progress = timestamp - start;
            const percentage = Math.min(progress / duration, 1);
            const value = Math.floor(percentage * target);
            $el.innerHTML = value.toLocaleString();
            if (progress < duration) {
                window.requestAnimationFrame(step);
            }
        };
        window.requestAnimationFrame(step);
    })">
    <span x-ref="el">0</span>
</div>

字符串

相关问题