проблема с плагином jquery |плагин работает только для последнего элемента span на странице - PullRequest
1 голос
/ 06 сентября 2010

вот небольшая демонстрация проблемы: 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 Ответ

1 голос
/ 06 сентября 2010

Основная проблема здесь:

$toAnimate = jQuery(this);

Он объявляет это как глобальную переменную, которая заменяет каждый цикл, так что в итоге она корректно анимирует только последнюю. Исправление очень простое, просто добавьте var, что делает его локальной переменной, как это было задумано, например:

var $toAnimate = $(this);

Я использую $ здесь, потому что мы находимся в закрытии, а остальные плагины используют его ... это просто изменение согласованности. Вы можете увидеть исправленную версию, работающую здесь .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...