2012-12-05 73 views
0

我想通過單擊菜單外部來關閉我的Javascript菜單。我正在使用this menu。我不是專業的,請告訴我如何改變我的代碼來做到這一點:通過單擊菜單外部關閉Javascript菜單

$("#theme_select").click(function() { 
    if (theme_list_open == true) { 
    $(".center ul li ul").fadeOut(); 
    theme_list_open = false; 
    } else { 
    $(".center ul li ul").show(); 
    theme_list_open = true; 
    } 
    return false; 
}); 
$("#theme_list ul li a").click(function() { 
    var theme_data = $(this).attr("rel").split(","); 
    $("li.purchase a").attr("href", theme_data[1]); 
    $("li.remove_frame a").attr("href", theme_data[0]); 
    $("#iframe").attr("src", theme_data[0]); 
    $("#theme_list a#theme_select").text($(this).text()); 
    $(".center ul li ul").hide(); 
    theme_list_open = false; 
    return false; 
}); 

回答

0

好像你用$("#theme_select").click(function() {兩種打開和關閉菜單。並使用$("#theme_list ul li a").click(function() {來處理點擊菜單項,這將關閉菜單。

實際上,您的問題有簡單的解決方案。使用$("#theme_select").click僅用於打開菜單,並且$("#theme_list ul li a")用於處理鏈接,並引入$(window).click關閉菜單。

function checkAndCloseMenu(evt) { 
    var dropmaker = $('#theme_select')[0]; 
    for (var node = evt.target; node != document.body; node = node.parentNode) 
    if (node == dropmaker) return false; // check if click in the dropmaker 
    $('.center ul li ul').fadeOut(); 
    $(window).unbind('click', checkAndCloseMenu); 
} 
$("#theme_select").click(function() { 
    $(".center ul li ul").show(); 
    $(window).click(checkAndCloseMenu); 
}); 
$("#theme_list ul li a").click(function() { 
    var theme_data = $(this).attr("rel").split(","); 
    $("li.purchase a").attr("href", theme_data[1]); 
    $("li.remove_frame a").attr("href", theme_data[0]); 
    $("#iframe").attr("src", theme_data[0]); 
    $("#theme_list a#theme_select").text($(this).text()); 
    return false; 
}); 

PS:可能是你應該給菜單和menuitems一些類名,你的選擇器是痛苦的閱讀。

1

如果您想在單擊iframe區域時關閉該菜單,則必須在iframe中執行該操作。試試把它放在你的iframe的文件準備功能中:

$("html").click(function() { 
    $(".center ul li ul", window.parent.document).fadeOut(); 
    window.parent.theme_list_open = false; 
}); 
相關問題