如何使用Jquery编写'if not clicked'或'if clicked outside element'? [英] How do I write 'if not clicked' or 'if clicked outside element', using Jquery?

查看:69
本文介绍了如何使用Jquery编写'if not clicked'或'if clicked outside element'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了如何阻止我的菜单执行fadeOut()函数的问题。当我单击菜单上的主链接打开子菜单时,它会淡出。以下是代码目前的样子:

I'm kind of stuck on a problem of how to stop my menu from executing the fadeOut() function. When I click the main links on my menu to open the submenu it just fades out. Here is how the code looks at the moment:

    $('a.main-menu-item').click(function(){

    if($('.rtmenu:visible')){

        $('.rtmenu').click(function(e) { e.stopPropagation(); });

        $(document).click(function() {
            $('.rtmenu').fadeOut(200);
        });
    }
})

任何人都可以告诉我如何写'如果没有点击a.main-menu-item'在哪里说'文件'?

Can anyone tell me how I can write 'if not clicked a.main-menu-item' where it says 'document'?

多赞赏

解决方案发现!

$('.rtmenu').click(function(e) { e.stopPropagation(); });
$('.rtmenu').mouseout(function(){ 
     $(document).one('click',function() { $('.rtmenu').fadeOut(200); }); 
 })


推荐答案

有一个看看Ben Alman的外部事件插件。它允许您定义一系列事件,而不仅仅是单击事件。有了它,你的代码看起来像这样:

Have a look at Ben Alman's "outside events" plugin. It allows you to define a range of events, not just click events. With it, your code would look something like this:

$('.rtmenu').bind('clickoutside', function() {
    $(this).fadeOut(200);
});

顺便说一下,你不应该在菜单的click事件中设置绑定,这个每次单击菜单选项时都会附加另一个处理程序。您的代码应替换为:

As an aside, you shouldn't set up the bind inside the click event for the menu, this will attach another handler every time the menu option is clicked. Your code should be replace with something like:

$('a.main-menu-item').click(function(){
    // Show menu item
});
$('.rtmenu').bind('clickoutside', function() {
    $(this).fadeOut(200);
});

这篇关于如何使用Jquery编写'if not clicked'或'if clicked outside element'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆