JQuery синхронная анимация

Более легкий способ установить это "по всему сайту" состоял бы в том, чтобы возможно сделать следующее в начальной загрузке или возможно основе zend_controller:

<?php    
$translateValidators = array(
                        Zend_Validate_NotEmpty::IS_EMPTY => 'Value must be entered',
                        Zend_Validate_Regex::NOT_MATCH => 'Invalid value entered',
                        Zend_Validate_StringLength::TOO_SHORT => 'Value cannot be less than %min% characters',
                        Zend_Validate_StringLength::TOO_LONG => 'Value cannot be longer than %max% characters',
                        Zend_Validate_EmailAddress::INVALID => 'Invalid e-mail address'
                    );
    $translator = new Zend_Translate('array', $translateValidators);
    Zend_Validate_Abstract::setDefaultTranslator($translator);
?>
20
задан Elazar Leibovich 20 October 2009 в 11:53
поделиться

5 ответов

jQuery cannot make synchronous animations.

Remember that JavaScript runs on the browser's UI thread.

If you make a synchronous animation, the browser will freeze until the animation finishes.

Why do you need to do this?

You should probably use jQuery's callback parameter and continue your method code in the callback, like this:

function doSomething() {
    var thingy = whatever;
    //Do things
    $('something').animate({ width: 70 }, function() {
        //jQuery will call this method after the animation finishes.
        //You can continue your code here.
        //You can even access variables from the outer function
        thingy = thingy.fiddle;
    });
}

This is called a closure.

26
ответ дан 30 November 2019 в 00:14
поделиться

Я согласен с @SLaks по этому поводу. Вы должны использовать обратные вызовы jQuery для заданных анимаций, чтобы создать синхронную анимацию. По сути, вы можете взять все, что у вас есть для текущей анимации, и разделить ее следующим образом:

$yourClass = $('.yourClass');
$yourClass.animate({
    width: "70%"
}, 'slow', null, function() {
    $yourClass.animate({
        opacity: 0.4
    }, 'slow', null, function() {
        $yourClass.animate({
            borderWidth: "10px"
        });
    });
});
1
ответ дан 30 November 2019 в 00:14
поделиться

jQuery предоставляет "пошаговый" обратный вызов для своего метода .animate (). Вы можете подключиться к этому для синхронной анимации:

jQuery('#blat').animate({
  // CSS to change
  height: '0px'
},
{
  duration: 2000,
  step: function _stepCallback(now,opts) {
    // Stop browser rounding errors for bounding DOM values (width, height, margin, etc.)
    now = opts.now = Math.round(now);

    // Manipulate the width/height of other elements as 'blat' is animated
    jQuery('#foo').css({height: now+'px'});
    jQuery('#bar').css({width: now+'px'});
  },
  complete: function _completeCallback() {
    // Do some other animations when finished...
  }
}
2
ответ дан 30 November 2019 в 00:14
поделиться

Думаю, вам стоит взглянуть на метод jQuery queue () .

В документе queue () не только объясняется, что анимация jQuery на самом деле не блокирует пользовательский интерфейс, а фактически ставит их в очередь одна за другой.

Он также предоставляет способ сделать ваши анимации и вызовы функций последовательными (это мое лучшее понимание того, что вы подразумеваете под « синхронный »), например:

$("#myThrobber")
    .show("slow")                 // provide user feedback 
    .queue( myNotAnimatedMethod ) // do some heavy duty processing
    .hide("slow");                // provide user feedback (job's 

myNotAnimatedMethod() { // or animated, just whatever you want anyhow...
    // do stuff
    // ...

    // tells #myThrobber's ("this") queue your method "returns", 
    // and the next method in the queue (the "hide" animation) can be processed
    $(this).dequeue();

    // do more stuff here that needs not be sequentially done *before* hide()
    // 
}  

Это, конечно, перебор с асинхронная обработка; но если ваш метод на самом деле является простым старым синхронным методом javascript, это может быть способ сделать это.

Надеюсь, это поможет, и извините за мой плохой английский ...

6
ответ дан 30 November 2019 в 00:14
поделиться

Я наткнулся на это http://lab.gracecode.com/motion/. Действительно прост в использовании и отлично работает в сочетании с jquery.

EDIT Ссылки кажутся мертвыми. Если я правильно проследил путь по архиву wayback, код находится по адресу https://github.com/feelinglucky/motion

0
ответ дан 30 November 2019 в 00:14
поделиться
Другие вопросы по тегам:

Похожие вопросы: