简体   繁体   English

单击页面上任何位置时关闭div

[英]Close a div when clicked anywhere on page

I have a search box that selects users and sends them into a div on my page which obviously opens with the script. 我有一个搜索框,可以选择用户并将它们发送到我页面上的div中,这显然会随脚本打开。 But I would like the box to close if the user clicks outside of the div anywhere on my sites page. 但是如果用户在我的网站页面上的任何位置点击div之外,我希望该框关闭。 I've played around with a few ideas but haven't got what I'm looking for. 我玩了几个想法,但没有得到我想要的东西。

HTML HTML

<input type="text" id="search_txt" placeholder="Search for friends" class="blog_input_field" onKeyUp="dosearch(document.getElementById('search_txt').value,'ajaxsearch_results');"><hr>
<div class="searchresults" id="ajaxsearch_results">

REQUEST FUNCTION 请求功能

function dosearch(text,containerid){
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();

    } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4) {
            //alert(xmlhttp.responseText);
            document.getElementById(containerid).innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","include/search.people.php?t="+text,true);
    xmlhttp.send();

}

In jquery You can do something like this: 在jquery你可以做这样的事情:

$(document).click(function(){
   $('.searchresults').hide();   
});

$('.searchresults').click(function(e){
    e.stopPropagation();
});

This can be done with raw JS, no need for Jquery. 这可以使用原始JS完成,不需要Jquery。 You hook the onmousedown or on click, and take advantage of the fact that JS events bubble up, eventually (unless blocked) to the document. 你挂钩onmousedown或点击,并利用JS事件冒泡的事实,最终(除非被阻止)到文档。 So: 所以:

document.onmousedown (or onclick) = function (e) {

  if (!e) e = window.event; // for browser compatibility

  target = (e.target ) ? e.target : e.srcElement; // again for browser compat..

  // note - could be child of div, too: see fine print    
  if (e.target.id != "divIDgoesHere")
      document.getElementById('divIDgoesHere').style.display = "none" ;
      // or other hide
}

The fine print: 细则:

  • if you click inside the div, the target might be some inner child of the div. 如果你在div中单击,目标可能是div的一个内部子项。 In which case, you can iterate over parentNode till you get to the search div, and ignore those requests. 在这种情况下,您可以遍历parentNode,直到到达搜索div,并忽略这些请求。

  • you could also remove the div altogether (div.parentNode.removeChild(div)). 你也可以完全删除div(div.parentNode.removeChild(div))。

  • you'll need to tweak the code some. 你需要调整一些代码。 Nothing major. 没什么大不了的。

Hope this helps 希望这可以帮助

TG TG

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

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