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

时间:2012-08-24 22:12:29

标签: javascript jquery ajax html

我有一个搜索框,用于选择用户并将其发送到我页面上的div中,这显然会随脚本打开。但是如果用户在我的网站页面上的任何位置点击div之外,我希望该框关闭。我已经玩了一些想法,但没有得到我正在寻找的东西。

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">

请求功能

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();

}

2 个答案:

答案 0 :(得分:8)

在jquery中你可以这样做:

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

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

答案 1 :(得分:4)

这可以使用原始JS完成,不需要Jquery。你挂钩onmousedown或点击,并利用JS事件冒泡的事实,最终(除非被阻止)到文档。所以:

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
}

小字:

  • 如果你在div中单击,目标可能是div的内部子项。在这种情况下,您可以迭代parentNode,直到找到搜索div,并忽略这些请求。

  • 你也可以完全删除div(div.parentNode.removeChild(div))。

  • 你需要调整一些代码。没什么大不了的。

希望这有帮助

TG

相关问题