如何关闭外部点击此菜单? [英] How to close this menu clicking outside?

查看:139
本文介绍了如何关闭外部点击此菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个菜单:

CSS

  #message {
display:none;
位置:绝对;
width:120px;
背景:#fff;
颜色:#000;
font-weight:bold;
}

当我点击它时会打开#message。
我的问题是关闭这个东西。



JS:

  $(#subm)。 b top:55,
left:evt.pageX - 55
})。show();
});

});

我尝试将上面的代码放在上面的函数中:


$ b $ ($('#message')。is(:visible)){$ b $ $ $'
$('#message')。hide();
}
});

但没有任何事情发生,显然菜单是在同一时间打开和关闭的。
出了什么问题?我怎么能关闭这个菜单点击外部消息框,甚至在跨班级?



JSFiddle

解决方案

您可以将点击处理程序绑定到文档关闭它:



示例: https://jsfiddle.net/jmpf1usu/4/

  $(#subm)。点击(函数(evt){
$(#message).css({
top:55,
left:evt.pageX + 55
})。show );

evt.stopPropagation();
});

$(document).click(function(){
$(#message)。hide();
});

evt.stopPropagation()点击从不到达文档,因此立即触发它再次关闭。


I have this menu:

CSS

#message { 
 display: none; 
 position: absolute; 
 width: 120px; 
 background: #fff; 
 color: #000; 
 font-weight: bold; 
}

When I click in it opens #message. My problem is to close this thing.

JS:

$(function() {

  $("#subm").click(function(evt) {
    $("#message").css({
      top: 55,
      left: evt.pageX - 55
    }).show();
  });

});

I try to put this code inside function above:

  $('html').click(function(evt) {
    if($('#message').is(":visible")) {
        $('#message').hide();
    }
  });

but nothing is happening, apparently menu is opening and closing in the same time. What is wrong? how can I close this menu clicking outside message box or even in span class?

JSFiddle

解决方案

You can bind a click handler to the document to close it:

Example: https://jsfiddle.net/jmpf1usu/4/

  $("#subm").click(function(evt) {
    $("#message").css({
      top: 55,
      left: evt.pageX + 55
    }).show();

      evt.stopPropagation();
  });

  $(document).click(function(){
      $("#message").hide();
  });

evt.stopPropagation()is required so that the click never reaches the document, thus immediately triggering it to close again.

这篇关于如何关闭外部点击此菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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