【问题标题】:Hide a toggle whenever I click outside the menu or click on any menu item using jQuery每当我在菜单外单击或使用 jQuery 单击任何菜单项时隐藏切换
【发布时间】:2015-12-11 08:36:51
【问题描述】:

我在网页左侧创建了一个切换窗口。每当我单击菜单中的任何锚标记或单击菜单栏外时,我都想隐藏切换窗口。

我已经在 J​​SFiddle 中上传了我的代码。相关代码如下。

http://jsfiddle.net/66db9vec/

$(window).load(function(){
    $("[data-toggle]").click(function() {
        var toggle_el = $(this).data("toggle");
        $(toggle_el).toggleClass("open-sidebar");
    });
});

【问题讨论】:

    标签: jquery html css toggle


    【解决方案1】:

    这应该可行。该脚本基本上检查单击的元素是否是切换图标并切换类,如果不是 - 它会删除它(不再切换以避免在不希望时显示菜单)。

    $(document).mouseup(function (e) {
        var toggle_el = $("[data-toggle]");
        var container = $("[data-toggle]").data("toggle");
    
        if (!toggle_el.is(e.target)) // if the target of the click isn't the container...
        {        
            if($(container).hasClass("open-sidebar")) {
                $(container).removeClass("open-sidebar"); 
            }
        }
        else {
            $(container).toggleClass("open-sidebar");
        }
    });
    

    【讨论】:

    • 我还有一个问题。它不适用于 iframe。我该如何解决这个...??
    • 不客气!您能否再解释一下您在什么情况下使用 iframe?
    • 我在同一页面中使用 iframe,当我单击 iframe 时它不起作用。看到这个小提琴jsfiddle.net/66db9vec/4
    • 在 iframe 上处理事件很棘手,但您可以使用名为 .contents() 的 jQuery 方法,在 iframe 元素上使用该方法时会返回 iframe 的文档。这是更新的小提琴:jsfiddle.net/66db9vec/8
    猜你喜欢
    • 2022-11-03
    • 2013-06-20
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 2017-06-30
    相关资源
    最近更新 更多