单击菜单外部关闭Javascript菜单

时间:2012-12-05 03:09:15

标签: javascript drop-down-menu click

我想通过单击菜单外部来关闭我的Javascript菜单。我正在使用this menu。我不专业,请告诉我如何更改我的代码:

$("#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;
});

2 个答案:

答案 0 :(得分:1)

如果要在单击iframe区域时关闭该菜单,则必须在iframe中执行此操作。尝试将其放入iframe的文档就绪函数中:

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

答案 1 :(得分: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一些类名,你的选择器很难阅读。

相关问题