繁体   English   中英

用户在div标签外单击时隐藏div标签

[英]Hiding div tag when the user clicks outside the div tag

我有一个div标签,并在自定义网格中填充搜索结果,该网格位于该divtag中。

当用户单击搜索按钮时,我正在上述div标签中显示结果。

我要求用户在div标签外单击时关闭上述div标签。

它类似于Google搜索自动完成。

提前致谢。

基本思想

  1. 在body标签上关联一个onclick事件以隐藏div。
  2. 在div标签上关联一个onclick事件,并停止事件冒泡。

查看活动顺序

停止事件冒泡

在Microsoft模型中,必须将事件的cancelBubble属性设置为true。

window.event.cancelBubble = true

在W3C模型中,您必须调用事件的stopPropagation()方法。

e.stopPropagation()

在jQuery中,如下所示:

$('body').click(function(ev){
  if (!$(this).hasClass('your_result_container_classname') {
    // code to hide result div
    $('body').unbind('click'); // remove event handler. add again when results shown.
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM