jquery插件问题|该插件仅适用于页面上的最后一个span元素

时间:2010-09-05 22:26:30

标签: jquery jquery-plugins

这是一个问题的小演示:textAnimation Demo 这是插件代码:

(function($) {
    $.fn.textAnimation = function(options) {
        // debug(this);
        // build main options before element iteration
        var opts = $.extend({}, $.fn.textAnimation.defaults, options);

        // iterate and reformat each matched element
        return this.each(function() {
            $toAnimate = jQuery(this);
            $toAnimateText = $toAnimate.text();
            $toAnimateTextLength = $toAnimateText.length;
            $toAnimate.text("");

            var show = false;
            var counter = 0;
            var char = new Array();
            var newColor;
            var $animation = null;

            // build element specific options
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

            for (i=0; i<$toAnimateText.length; i++) {
                char[i] = $toAnimateText.charAt(i);
                $toAnimate.append('<span class="' + i +  '">' + char[i] + '</span');
            }

            function runIt(show) {
                $animation = $toAnimate.children('span.' + counter);

                newColor = (show == true) ? o.fromColor : o.toColor;

                $animation
                    .css("color", newColor)
                    //.delay(120, countUp) // this seems to be a jquery bug - after the first loop countUp is not called
                    .animate({left:'0'}, 120, countUp) // took the left because it makes no problem in all browsers

                function countUp() {
                    counter++;

                    if (counter >= $toAnimateTextLength) {
                        counter = 0;
                        show = (show == false) ? true : false;
                    }

                    runIt(show);
                };
            };

            runIt(show);
        });
    };

    //
    // private function for debugging
    //
    function debug($obj) {
    if (window.console && window.console.log)
        window.console.log('textAnimation selection count: ' + $obj.size());
    };   

    //
    // plugin defaults
    //
    $.fn.textAnimation.defaults = {
        fromColor: '#223139',
        toColor: '#e6772b'
    };
//
// end of closure
//
})(jQuery);

1 个答案:

答案 0 :(得分:1)

主要问题在于:

$toAnimate = jQuery(this);

它将此声明为一个全局变量,它取代了每个循环,因此它最终只能正确地动画最后一个变量。修复很简单,只需添加var,这使得它成为它的本地变量,如下所示:

var $toAnimate = $(this);

我在这里使用$,因为我们处于关闭状态,插件的其余部分使用它......这只是一个一致性变化。 You can see the fixed version working here