如何隐藏div点击或点击div

时间:2013-11-03 07:02:24

标签: javascript show-hide

此代码显示从按钮点击的div,但我想在用户点击其他地方或者点击div中的项目时隐藏div。

function show_menu(){
    var menu = document.getElementById('dropdown_menu');

    if(menu.style.display == 'block'){
        menu.style.display = 'none';
    }else {
        menu.style.display = 'block';                    
    }
}

3 个答案:

答案 0 :(得分:1)

鉴于这种简化的HTML:

<div id="myDiv"> myDiv </div>

使用这个simplfied javascript:

var div = document.getElementById("myDiv");

// event gets passed and represents the DOM event

document.onclick = function( event ){
    console.log("outside");
    if( event.toElement !== div ){
        div.style.visibility = "hidden";
    }
};

div.onclick = function( event ){
    console.log("inside");
    event.toElement.style.visibility = "hidden";
}

这基本上隐藏了你点击它或不点击它,所以我不完全确定它的应用程序。所以简而言之,如果你想隐藏某个人在里面或外面点击的内容,只需使用以下内容,但是再一次,我认为它没有用处:

document.onlick = function(){ 
  document.getElementById("myDiv").style.visibility = "hidden";
}

答案 1 :(得分:0)

使用.children() selector
http://api.jquery.com/children/

演示:http://jsfiddle.net/WMJc5/2/

<html lang="en">
<head>
  <meta charset="utf-8">
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
 <style>
  #mydiv p,#mydiv a,#mydiv h3,#mydiv div,#mydiv span{background-color:red;}
 </style>
</head>
<body>
    <div id="mydiv" style="border:1px solid;">
    <p>p tag</p>
      <a >a tag</a><br>
      <h3>H3</h3><br>
      <div>inner div</div><br>
      <span>444</span>
    </div>
   <script>
   $( "#mydiv *" ).click(function () {$( "#mydiv" ).hide();});
  </script>
</body>
</html>

答案 2 :(得分:0)

假设你的评论告诉我们你真正想要的东西,那就是这样的

Live Demo

$(function() {
  $("#to_folder").on("change",function() {
    $(".folder").hide();
    var folderId = this.value;
    if (folderId !="") {
      $("#folder"+folderId).show();
    }
  });
  $("#to_folder").trigger("change"); // show/hide whatever matches the select
});
使用

<select id="to_folder" name="to_folder"> 
  <option value="">- move to folder -</option> 
  <option value="0"> / </option> 
  <option value="1">folder 1</option> 
  <option value="2">folder 2</option> 
</select>
<div class="folder" id="folder0">/</div>
<div class="folder" id="folder1">1</div>
<div class="folder" id="folder2">2</div>

最初隐藏了div