显示焦点上的菜单,并在失焦时隐藏或单击菜单以外的其他菜单

时间:2015-09-21 13:40:20

标签: javascript jquery html css

我在div(#lorem-ipsum-wrapper)聚焦时尝试显示菜单(#content),如果没有点击div或菜单,再次隐藏菜单

JS:

$(document).ready(function() {
  console.log('ready');

  $('#content').on("focus", function(event) {
    $('#lorem-ipsum-wrapper').css("display", "block");
    event.stopPropagation();
  });

  $(document).on("click", function() {
    $('#lorem-ipsum-wrapper').css("display", "none");
  });
});

演示codepent.io

但问题是,只要#content成为焦点,菜单就会显示,然后再次隐藏自己。是不是用stopPropagation()方法阻止了这个?我究竟做错了什么?非常感谢您的帮助。谢谢。

2 个答案:

答案 0 :(得分:2)

这有帮助吗?

{ max-width: 100%; }

或者您可以使用模糊事件:

 $(document).click(function(e) {
    var e = $(e.target), eid = e.attr("id");
    if (!e.parents("#lorem-ipsum-wrapper").length && !e.parents("#content-wrapper").length && eid !== "content-wrapper" && eid !== "lorem-ipsum-wrapper") {
      $('#lorem-ipsum-wrapper').css("display", "none");
    }
  });

答案 1 :(得分:0)

如果我没有误解,您希望隐藏#lorem-ipsum-wrapper如果未点击#content,则点击#lorem-ipsum-wrapper时显示#content。然后,您的代码应为:

$(document).ready(function() {
  console.log('ready');
   $('#lorem-ipsum-wrapper').css('display','none');

  $('#content').on("focus", function(event) {
    $('#lorem-ipsum-wrapper').css('display','block');
  });

  $('#content').on("blur", function() {
    $('#lorem-ipsum-wrapper').css("display", "none");
 });
  $('#lorem-ipsum-wrapper').on("click",function(){
    $(this).css("display","block");
});

<强>解释

第三行确保在执行任何代码之前未显示lorem-ipsum-wrapper

只要焦点位于#lorem-ipsum-wrapper,第四行和第五行就会显示#content

当用户点击页面上的其他位置或使lorem-ipsum-wrapper失去焦点时,第7行和第8行会隐藏#lorem-ipsum-wrapper