在外面单击时隐藏 div 类



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>

我想在div 外部单击时隐藏此 #nav_dropdown_items。我该怎么办?谢谢!

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>

由于您已经在引用 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");
}

最新更新