Jquery切换自定义动画
我有这个动画,我想点击链接时触发。 当我单独运行动画时,它工作正常。 但是使用jquery toggle()
,它不再起作用了。 谁能轻易明白为什么?
没有toggle()
它可以工作(单独运行):
$('#sign-in-fx').click(function() { $('.login_form').animate({ width: '273' }, 'slow', 'easeInOutQuart'); //$('.login_form').animate({ width: '1' }, 'slow', 'easeInOutQuart'); });
使用toggle()
没有任何反应:
$('#sign-in-fx').click(function() { $('.login_form').toggle( function() { $(this).animate({ width: '273' }, 'slow', 'easeInOutQuart') }, function() { $(this).animate({ width: '1' }, 'slow', 'easeInOutQuart') } ); });
这类似于jQuery切换动画
现在我觉得这是你原本想做的事情:
$('#sign-in-fx').toggle( function() { $('.login_form').animate({ width: '273' }, 'slow', 'easeInOutQuart') }, function() { $('.login_form').animate({ width: '1' }, 'slow', 'easeInOutQuart') } );
您在元素上调用toggle()
来设置动画,但必须在将接收click
事件的元素上调用它。
toggle()
使用了你使用它的方式, 不推荐使用 !
使用标志,直接切换动画宽度,如下所示:
var flag = true; $('#sign-in-fx').on('click', function() { $('.login_form').stop(true, true) .animate({ width: flag?'273':'1' }, 'slow', 'easeInOutQuart'); flag=!flag; });
小提琴
或者如果你不喜欢全局变量,你总是可以使用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); });
小提琴
我想你也可以这样做:
$('#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'); } } });
你确定它是在document.ready
上完成的吗? 你的代码似乎很好。
$(function () { $('.login_form').toggle( function() { $(this).animate({ width: '273' }, 'slow', 'easeInOutQuart') }, function() { $(this).animate({ width: '1' }, 'slow', 'easeInOutQuart') } ); });