到达HTML文件中的某个点时动画编号和文本

时间:2016-04-05 08:53:03

标签: javascript jquery html numbers nan

我想在向下滚动HTML文件并到达某个部分时计算带有文本的数字。代码如下所示:

<h3 class="count">25 Years</h3>
<p>On the Road...</p>

<h3 class="count">143 Million</h3>
<p>Transactions worldwide 2015</p>
$('.count').each(function() {
    $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});

问题是当我只输入一个数字时,我只能得到正确的结果。如果我输入25 Years之类的字符串,则会输出NaN

我的代码有什么建议吗?

var targetOffset = $(".company-numbers").offset().top;

        var $w = $(window).scroll(function(){
            if ( $w.scrollTop() > targetOffset ) {
                (function () {
                    $('.count').each(function () {
                        $(this).prop('Counter',0).animate({
                            Counter: $(this).text()
                        }, {
                            duration: 4000,
                            easing: 'swing',
                            step: function (now) {
                                $(this).text(Math.ceil(now));
                                return false;
                            }
                        });
                    });
                })();
            } else {
                return false;
            }
        })

3 个答案:

答案 0 :(得分:0)

问题是因为你的jQuery代码希望能够将值解析为整数。尝试将值计入其自己的元素中,例如<span>,然后在这些值上调用jQuery逻辑。

<h3><span class="count">25</span> Years</h3>
<p>On the Road...</p>

<h3><span class="count">143</span> Million</h3>
<p>Transactions worldwide 2015</p>

答案 1 :(得分:0)

如果您希望像在函数内部使用键值创建数组或JSON一样操作,则必须为元素指定数字值。

答案 2 :(得分:0)

请检查此代码,你真的想要这样吗? 让我知道!!!

<h3 class="count">25 Years</h3>
<p>On the Road...</p>

<h3 class="count">143 Million</h3>
<p>Transactions worldwide 2015</p>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
   $('.count').each(function () {
                $(this).prop('Counter',0).animate({
                    Counter: $(this).text().match(/\d/g).length
                }, {
                    duration: 4000,
                    easing: 'swing',
                    step: function (now) {
                        $(this).text(Math.ceil(now));
                    }
                });
            });
            </script>

或者如果您想计算总字符数,请更改&#34; counter&#34;属性。

Counter: $(this).html().length
相关问题