J’ai cette animation que je voudrais déclencher en cliquant sur un lien. Lorsque je lance les animations séparément, cela fonctionne bien. Mais en utilisant le jquery toggle()
, cela ne fonctionne plus. Quelqu’un peut-il facilement voir pourquoi?
Sans toggle()
cela fonctionne (exécuté séparément):
$('#sign-in-fx').click(function() { $('.login_form').animate({ width: '273' }, 'slow', 'easeInOutQuart'); //$('.login_form').animate({ width: '1' }, 'slow', 'easeInOutQuart'); });
Avec toggle()
rien ne se passe:
$('#sign-in-fx').click(function() { $('.login_form').toggle( function() { $(this).animate({ width: '273' }, 'slow', 'easeInOutQuart') }, function() { $(this).animate({ width: '1' }, 'slow', 'easeInOutQuart') } ); });
Ceci est similaire à l’ animation à bascule jQuery
Maintenant, je pense que c’est ce que vous vouliez faire à l’origine:
$('#sign-in-fx').toggle( function() { $('.login_form').animate({ width: '273' }, 'slow', 'easeInOutQuart') }, function() { $('.login_form').animate({ width: '1' }, 'slow', 'easeInOutQuart') } );
Vous appeliez toggle()
sur l’élément à animer, mais il doit être appelé sur l’élément qui recevra l’événement click
.
toggle()
utilisé tel que vous l’utilisez, est obsolète !
Utilisez un drapeau et basculez la largeur animée directement, comme ceci:
var flag = true; $('#sign-in-fx').on('click', function() { $('.login_form').stop(true, true) .animate({ width: flag?'273':'1' }, 'slow', 'easeInOutQuart'); flag=!flag; });
VIOLON
Ou si vous n’aimez pas les globales, vous pouvez toujours utiliser data ():
$('#sign-in-fx').on('click', function() { var flag = $('.login_form').data('flag')!=undefined?$('.login_form').data('flag'):true; $('.login_form').stop(true, true) .animate({ width: flag?'273':'1' }, 'slow', 'easeInOutQuart') .data('flag', !flag); });
VIOLON
Je pense que vous pourriez aussi faire comme suit:
$('#sign-in-fx').click(function() { if (! $('.login_form').is(':animated')) { //if no animation running if ($('.login_form').width() > 1) { $('.login_form').animate({ width: '1' }, 'slow', 'easeInOutQuart'); } else { $('.login_form').animate({ width: '273' }, 'slow', 'easeInOutQuart'); } } });
Êtes-vous sûr que c’est fait sur document.ready
? Votre code semble bien.
$(function () { $('.login_form').toggle( function() { $(this).animate({ width: '273' }, 'slow', 'easeInOutQuart') }, function() { $(this).animate({ width: '1' }, 'slow', 'easeInOutQuart') } ); });