3 回答
TA贡献2080条经验 获得超4个赞
尝试以下解决方案。
.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}
.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
transition: 0.3s;
}
<script>
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}
window.addEventListener('click', function(e){
if (!document.getElementById('mySidenav').contains(e.target) && !document.getElementById('myMenu').contains(e.target)){
// Clicked in box
document.getElementById("mySidenav").style.width = "0px";
} else{
// document.getElementById("mySidenav").style.width = "0px";
}
});
</script>
<div id="mySidenav" class="sidenav">
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
<span style="font-size:30px;cursor:pointer" id="myMenu" onclick="openNav()">☰ open</span>
TA贡献1828条经验 获得超3个赞
你可以试试这样的
<style>
#mySidenav {
display: none;
}
</style>
<script>
document.body.addEventListener('click', function (e) {
if (e.target.parentNode.id === 'mySidenav') {
document.getElementById("mySidenav").style.display = "block";
e.preventDefault();
return;
}
document.getElementById("mySidenav").style.display = "none";
}, true);
function openNav() {
document.getElementById("mySidenav").style.display = "block";
}
</script>
<div id="mySidenav" class="sidenav">
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ open</span>
TA贡献1865条经验 获得超7个赞
$(function() {
$("#ham-icon").on("click", function(e) {
$("#mySidenav").addClass("cstm-w");
e.stopPropagation()
});
$(document).on("click", function(e) {
if ($(e.target).is("#ham-icon") === false) {
$("#mySidenav").removeClass("cstm-w");
}
});
});
.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}
.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
transition: 0.3s;
}
.cstm-w {
width: 250px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mySidenav" class="sidenav">
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
<span style="font-size:30px;cursor:pointer" id="ham-icon">☰ open</span>
添加回答
举报