【问题标题】:Close a div when clicked anywhere on page单击页面上的任意位置时关闭 div
【发布时间】:2012-08-25 06:48:29
【问题描述】:

我有一个搜索框,可以选择用户并将他们发送到我页面上的一个 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();

}

【问题讨论】:

  • 上面的代码给了我同样的问题。当我在搜索中单击时,它没有显示任何结果并隐藏了我的页面顶部。
  • 我已经发布了下面的代码,请检查。

标签: javascript jquery ajax html


【解决方案1】:

在 jquery 中你可以这样做:

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

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

【讨论】:

  • 太棒了。就像我需要的那样工作。简单,但有效。很快就会接受。谢谢
  • 我还可以问另一个与这篇文章有关的问题吗?窗口关闭后,我再次尝试搜索。除非我刷新页面,否则我无法搜索它不会显示。我怎样才能防止这种情况发生?
  • 哪个窗口?你的意思是浏览器?你能详细说明一下吗?
  • 对不起。分区。一旦我点击退出并尝试搜索另一个用户,它不会显示任何结果。我只能在刷新页面时显示新结果。这是缓存问题吗?
  • 好的。根据您之前提到的要求,当用户单击该特定 div 以外的任何其他位置时,您希望隐藏该 div。因此,当您尝试搜索新用户时,它不会显示该 div,因为它是隐藏的,您需要删除隐藏.. $('.searchresults').show()。
【解决方案2】:

这可以用原始 JS 完成,不需要 Jquery。您将 onmousedown 或 on click 挂钩,并利用 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

【讨论】:

    猜你喜欢
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    相关资源
    最近更新 更多