单击外部时隐藏div类

时间:2018-05-14 16:12:06

标签: javascript



function nav_category_show() {
    var x = document.getElementById("nav_dropdown_items");
    if (x.className.indexOf("w3-show") == -1) {
        x.className += " w3-show";
    } 

    else { 
        x.className = x.className.replace(" w3-show", "");
    }   
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
    
    
<span onclick="nav_category_show()">click here<i class="fa fa-bars"></i></span>

<div id="nav_dropdown_items" class="w3-animate-zoom w3-dropdown-content w3-bar-block w3-card-4">
			<a href="#" class="w3-bar-item w3-button">Link 1</a>
            
</div>
&#13;
&#13;
&#13;

我想在点击div外面时隐藏这个#nav_dropdown_items。我该怎么办?谢谢!

2 个答案:

答案 0 :(得分:1)

nav_category_show函数中添加类后,使用event.stopPropagation停止事件传播。

body添加另一个事件,然后从nav_category_show

中删除该课程

function nav_category_show(e) {
  var x = document.getElementById("nav_dropdown_items");
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else {
    x.className = x.className.replace("w3-show", "");
  }
  e.stopPropagation();
}
document.body.addEventListener('click', function() {
  document.getElementById("nav_dropdown_items").classList.remove('w3-show');

})
body {
  width: 500px;
  height: 500px;
  border: 1px solid red;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>


<span onclick="nav_category_show(event)">click here<i class="fa fa-bars"></i></span>

<div id="nav_dropdown_items" class="w3-animate-zoom w3-dropdown-content w3-bar-block w3-card-4">
  <a href="#" class="w3-bar-item w3-button">Link 1</a>

</div>

答案 1 :(得分:0)

由于您已经引用了jquery,因此您可以使用它来轻松隐藏/显示选择的div:

var target = $("#nav_dropdown_items");
if(target.hasClass("w3-show")) {
  target.hide();  // hides it
  target.removeClass("w3-show");
}
else {
  target.show();  //shows it
  target.addClass("w3-show");
}