【问题标题】:jQuery, animate and animate back. Call back function error? :SjQuery,动画和动画返回。回调函数错误? :S
【发布时间】:2015-02-12 13:11:11
【问题描述】:

我不知道我做了什么。这个想法是动画一个元素从一个位置滑入并在另一个元素被单击时滑回。我在原始事件函数的回调中应用了第二个事件。

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

如果你不关注,基本思路是这样的。

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

$('#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() 来运行滑入和滑出吗?

【问题讨论】:

  • 你在嵌套点击处理程序,坏主意!
  • 我是这么认为的 :p 你可以推荐另一种方法吗?
  • Rory 的回答对你不起作用吗?

标签: javascript jquery events animation callback


【解决方案1】:

这里不需要回调,只需将 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();
    });
});

Example fiddle

请注意,我使用了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();
        });
    }
});

Updated fiddle

【讨论】:

  • 哦,是的 :d 对不起,我现在觉得自己很愚蠢 XD 很久没做 DOM 了!!谢谢 :) 等一下,我刚刚意识到我的问题。两秒钟后我会改变我的问题。
  • @sourRaspberri 没问题,很高兴为您提供帮助:)
  • 发现了我的问题。 $('mobileList')#body 内,所以两者同时启动:p
  • 有没有我可以使用的选择器来选择除元素#mobileMenu 之外的所有内容? :d
  • 当其他任何内容被点击时,您是否试图隐藏mobileMenu
猜你喜欢
  • 2013-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-16
  • 2012-02-15
  • 2011-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多