jQuery,动画和动画返回.回调函数错误?:S

jQuery, animate and animate back. Call back function error? :S

本文关键字:动画 错误 函数 回调 返回 jQuery      更新时间:2023-09-27

我不知道自己做了什么。其想法是设置一个元素的动画,使其从某个位置滑入,并在单击另一个元素时滑回。我已经在原始事件函数的回调中应用了第二个事件。

但是,尽管有这种结构,第二个事件函数将运行,尽管我还没有单击回调函数中的第二个元素。

如果你没有遵循,基本的想法是这样的。

点击->滑入->外侧点击->滑出

$('#mobileList').click(function(){
    $('#mobileMenu').css({'display':'block'}).animate({
        'left':'30%'
    },500,function(){
        $('#body').click(function(){
            $('#mobileMenu').animate({
                'left':'100%'
            },500,function(){$('#mobileMenu').css({'display':"none"});/* I tried return false; here, failed to solve problem*/});
        });
    });         
});

启动CSS

nav#mobileMenu{display:none;width:70%;height:100%;background:#191820;color:#DCDCDC;position:fixed;top:0;left:100%;}

元素的结构。

<div id="body">
    <a id="mobileList>&#9776;</a>
    <!-- content here -->
</div>
<nav id="mobileMenu">
    <!-- content -->
</nav>

前两次尝试效果良好。下次我来跑步时,它会设置动画,然后立即设置动画。我真的不明白为什么,因为这是一个回调函数?:S

我认为这是因为元素#mobileList在元素#body内。

回拨电话还在吗?我可以停止寻找活动吗?

我应该使用queue()运行滑入和滑出吗?

这里不需要回调,只需单独挂起click处理程序即可:

$('#mobileList').click(function(){
    $('#mobileMenu').show().stop(true).animate({
        'left': '30%'
    }, 500);         
});
$('#body').click(function(){
    $('#mobileMenu').stop(true).animate({
        'left': '100%'
    }, 500, function() {
        $(this).hide();
    });
});

小提琴示例

请注意,我使用了show/hide而不是css,并添加了对stop()的调用,以防止在动画期间连续单击时队列被填满。


更新

要在单击其他任何位置时隐藏菜单,需要将事件处理程序附加到document并检查e.target以查看是什么元素导致了该事件。如果它在菜单之外,就把它隐藏起来。

$('#mobileList').click(function (e) {
    e.stopPropagation();
    $('#mobileMenu').show().stop(true).animate({ 'left': '30%' }, 500);
});
$(document).click(function (e) {
    var $menu = $('#mobileMenu');
    if (!$menu.is(e.target) && !$menu.has(e.target).length) {
        $('#mobileMenu').stop(true).animate({ 'left': '100%' }, 500, function () {
            $(this).hide();
        });
    }
});

更新的fiddle