Принятый ответ обеспечивает отличную информацию, но здесь, похоже, есть несколько других морщин - различия между пониманием списка и выражениями генератора. Демонстрация, с которой я играл:
class Foo:
# A class-level variable.
X = 10
# I can use that variable to define another class-level variable.
Y = sum((X, X))
# Works in Python 2, but not 3.
# In Python 3, list comprehensions were given their own scope.
try:
Z1 = sum([X for _ in range(3)])
except NameError:
Z1 = None
# Fails in both.
# Apparently, generator expressions (that's what the entire argument
# to sum() is) did have their own scope even in Python 2.
try:
Z2 = sum(X for _ in range(3))
except NameError:
Z2 = None
# Workaround: put the computation in lambda or def.
compute_z3 = lambda val: sum(val for _ in range(3))
# Then use that function.
Z3 = compute_z3(X)
# Also worth noting: here I can refer to XS in the for-part of the
# generator expression (Z4 works), but I cannot refer to XS in the
# inner-part of the generator expression (Z5 fails).
XS = [15, 15, 15, 15]
Z4 = sum(val for val in XS)
try:
Z5 = sum(XS[i] for i in range(len(XS)))
except NameError:
Z5 = None
print(Foo.Z1, Foo.Z2, Foo.Z3, Foo.Z4, Foo.Z5)
Итак, это очень нестандартное решение, сочетающее эффекты отскока и подсветки. Я бы предпочел увидеть какую-то поддержку jquery для более простой комбинации этих эффектов, указав {queue:false}, но я не думаю, что это так просто.
Я взял jquery.effects.bounce.js и jquery.effects.highlight.js (из jquery-ui-1.8rc3) и объединил их код, как предложил DaveS, чтобы создать новый эффект под названием "hibounce". В моем тестировании он поддерживает все опции обоих эффектов, и они возникают одновременно. Это выглядит великолепно! Однако я не являюсь большим поклонником подобных решений из-за фактора обслуживания. Каждый раз, когда я буду обновлять jquery.ui, мне придется вручную обновлять и этот файл.
В любом случае, вот объединенный результат (jquery.effects.hibounce.js)
(function($) {
$.effects.hibounce = function(o) {
return this.queue(function() {
// Highlight and bounce parts, combined
var el = $(this),
props = ['position','top','left','backgroundImage', 'backgroundColor', 'opacity'],
mode = $.effects.setMode(el, o.options.mode || 'show'),
animation = {
backgroundColor: el.css('backgroundColor')
};
// From highlight
if (mode == 'hide') {
animation.opacity = 0;
}
$.effects.save(el, props);
// From bounce
// Set options
var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
var direction = o.options.direction || 'up'; // Default direction
var distance = o.options.distance || 20; // Default distance
var times = o.options.times || 5; // Default # of times
var speed = o.duration || 250; // Default speed per bounce
if (/show|hide/.test(mode)) props.push('opacity'); // Avoid touching opacity to prevent clearType and PNG issues in IE
// Adjust
$.effects.save(el, props); el.show(); // Save & Show
$.effects.createWrapper(el); // Create Wrapper
var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';
var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) / 3 : el.outerWidth({margin:true}) / 3);
if (mode == 'show') el.css('opacity', 0).css(ref, motion == 'pos' ? -distance : distance); // Shift
if (mode == 'hide') distance = distance / (times * 2);
if (mode != 'hide') times--;
// from highlight
el
.show()
.css({
backgroundImage: 'none',
backgroundColor: o.options.color || '#ffff99'
})
.animate(animation, {
queue: false,
duration: o.duration * times * 1.3, // cause the hilight to finish just after the bounces (looks best)
easing: o.options.easing,
complete: function() {
(mode == 'hide' && el.hide());
$.effects.restore(el, props);
(mode == 'show' && !$.support.opacity && this.style.removeAttribute('filter'));
(o.callback && o.callback.apply(this, arguments));
el.dequeue();
}
});
// Animate bounces
if (mode == 'show') { // Show Bounce
var animation = {opacity: 1};
animation[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
el.animate(animation, speed / 2, o.options.easing);
distance = distance / 2;
times--;
};
for (var i = 0; i < times; i++) { // Bounces
var animation1 = {}, animation2 = {};
animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance;
animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing);
distance = (mode == 'hide') ? distance * 2 : distance / 2;
};
if (mode == 'hide') { // Last Bounce
var animation = {opacity: 0};
animation[ref] = (motion == 'pos' ? '-=' : '+=') + distance;
el.animate(animation, speed / 2, o.options.easing, function(){
el.hide(); // Hide
$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
if(o.callback) o.callback.apply(this, arguments); // Callback
});
} else {
var animation1 = {}, animation2 = {};
animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance;
animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing, function(){
$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
if(o.callback) o.callback.apply(this, arguments); // Callback
});
};
el.queue('fx', function() { el.dequeue(); });
el.dequeue();
});
};
})(jQuery);
Теперь его можно использовать как любой другой эффект:
var el = $("#div1");
el.effect("hibounce", {color: "#F00", times: 5}, 100);
Вы можете попробовать следующее:
var els = $(".errorMsg");
setTimeout(function() {
els.effect("bounce", {times: 5}, 100);
}, 1);
setTimeout(function() {
els.effect("highlight", {color: "#ffb0aa"}, 300);
}, 1);
Это должно вызывать оба эффекта примерно одновременно, асинхронно.
Анимация очереди эффектов пользовательского интерфейса jQuery, так что напишите свою собственную версию функции отскока / выделения. Просто скопируйте исходный код из обеих функций в одну функцию, очистите код и каждый раз, когда он вызывает анимацию, убедитесь, что логика отскока и выделения присутствует вместе.