jQuery-在视口中使数字计数 [英] jquery - Make number count up when in viewport

查看:91
本文介绍了jQuery-在视口中使数字计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在视口中对数字进行计数,但是目前,我正在使用的脚本会在滚动时中断计数.

I'm trying to make a number count up when it's within the viewport, but currently, the script i'm using will interrupt the count on scroll.

我将如何制作它,以使其在视口内时忽略滚动并仅向上计数?这需要在移动设备上工作,因此即使用户在触摸时滚动也是如此.它不能中断计数.

How would I make it so that it will ignore the scroll and just count up when it's within the viewport? This needs to work on mobile, so even when a user is scrolling on touch. It cannot interrupt the count.

请在此处查看: http://jsfiddle.net/Q37Q6/27/

(function ($) {

$.fn.visible = function (partial, hidden) {

    var $t = $(this).eq(0),
        t = $t.get(0),
        $w = $(window),
        viewTop = $w.scrollTop(),
        viewBottom = viewTop + $w.height(),
        _top = $t.offset().top,
        _bottom = _top + $t.height(),
        compareTop = partial === true ? _bottom : _top,
        compareBottom = partial === true ? _top : _bottom,
        clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;

    return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));
};

})(jQuery);


// Scrolling Functions
$(window).scroll(function (event) {
function padNum(num) {
    if (num < 10) {
        return "" + num;
    }
    return num;
}

var first = 25; // Count up to 25x for first
var second = 4; // Count up to 4x for second
function countStuffUp(points, selector, duration) { //Animate count
    $({
        countNumber: $(selector).text()
    }).animate({
        countNumber: points
    }, {
        duration: duration,
        easing: 'linear',
        step: function () {
            $(selector).text(padNum(parseInt(this.countNumber)));
        },
        complete: function () {
            $(selector).text(points);
        }
    });
}

// Output to div
$(".first-count").each(function (i, el) {
    var el = $(el);
    if (el.visible(true)) {
        countStuffUp(first, '.first-count', 1600);
    }
});

// Output to div
$(".second-count").each(function (i, el) {
    var el = $(el);
    if (el.visible(true)) {
        countStuffUp(second, '.second-count', 1000);
    }
});

});

我认为,

推荐答案

您的示例比您所知道的要复杂.您正在以一种非常不寻常的方式来做事,这里,在自定义属性上使用jQuery animate方法作为计数器.这有点酷,但也使事情变得更加复杂.我不得不添加一些东西来理顺这种情况.

Your example is more complicated than you're aware, I think. You're doing things in a pretty unusual way, here, using a jQuery animate method on a custom property as your counter. It's kind of cool, but it also makes things a little more complicated. I've had to add a number of things to straighten up the situation.

  1. 我继续重写了可见的插件,主要是因为我不知道您的插件在做什么.这很简单!

  1. I went ahead and rewrote your visible plugin, largely because I had no idea what yours was doing. This one's simple!

当您的计数器变为可见状态时,它们将获得一个计数"类,以便在它们已经计数时不会在其上重新触发计数器.

When your counters become visible, they get a "counting" class so that the counter isn't re-fired on them when they're already counting.

我将对您具有自定义计数器动画的对象的引用保存到计数器的data属性.这很重要:没有该参考,动画在屏幕外播放时就无法停止.

I save a reference to the object you have your custom counter animation on to the data attribute of the counter. This is vital: without that reference, you can't stop the animation when it goes offscreen.

我在step函数中做了一些幻想,以跟踪剩余时间,以便即使计数器停止和启动,计数器也能以相同的速度运行.如果您的计数器运行了半秒,并且整个动画都设置为使用一秒钟,那么当它被中断并重新启动时,您只想在重新启动计数器时将其设置为半秒.

I do some fanciness inside the step function to keep track of how much time is left so that you can keep your counter running at the same speed even if it stops and starts. If your counter runs for half a second and it's set to use one second for the whole animation, if it gets interrupted and restarted you only want to set it to half a second when you restart the counter.

http://jsfiddle.net/nate/p9wgx/1/

(function ($) {

    $.fn.visible = function () {

        var $element = $(this).eq(0),
            $win = $(window),

            elemTop = $element.position().top,
            elemBottom = elemTop + $element.height(),

            winTop = $win.scrollTop(),
            winBottom = winTop + $win.height();

        if (elemBottom < winTop) {
            return false;
        } else if (elemTop > winBottom) {
            return false;
        } else {
            return true;
        }        
    };

})(jQuery);

function padNum(num) {
    if (num < 10) {
        return " " + num;
    }
    return num;
}


var $count1 = $('.first-count');
var $count2 = $('.second-count');

// Scrolling Functions
$(window).scroll(function (event) {
    var first = 25; // Count up to 25x for first
    var second = 4; // Count up to 4x for second

    function countStuffUp(points, selector, duration) {
        //Animate count
        var $selector = $(selector);
        $selector.addClass('counting');

        var $counter = $({
            countNumber: $selector.text()
        }).animate({
            countNumber: points
        }, {
            duration: duration,
            easing: 'linear',
            step: function (now) {
                $selector.data('remaining', (points - now) * (duration / points));
                $selector.text(padNum(parseInt(this.countNumber)));
            },
            complete: function () {
                $selector.removeClass('counting');
                $selector.text(points);

            }
        });

        $selector.data('counter', $counter);
    }

    // Output to div
    $(".first-count").each(function (i, el) {
        var el = $(el);
        if (el.visible() && !el.hasClass('counting')) {
            var duration = el.data('remaining') || 1600;
            countStuffUp(first, '.first-count', duration);
        } else if (!el.visible() && el.hasClass('counting')) {
            el.data('counter').stop();
            el.removeClass('counting');
        }
    });

    // Output to div
    $(".second-count").each(function (i, el) {
        var el = $(el);
        if (el.visible() && !el.hasClass('counting')) {
            var duration = el.data('remaining') || 1000;
            countStuffUp(second, '.second-count', duration);
        } else if (!el.visible() && el.hasClass('counting')) {
            el.data('counter').stop();
            el.removeClass('counting');
        }
    });
});

这里有很多东西.如果有什么不清楚的地方,随时问我问题.

There's a lot here. Feel free to ask me questions if anything's not clear.

这篇关于jQuery-在视口中使数字计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆