我试图生成一个侧栏,该侧栏通过单击除侧栏以外的其他所有东西(使用js或css)自动隐藏。

我的代码是:

<script>
function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
}
</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()">&#9776; open</span>


和CSS是:

<style>
.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;
}
</style>


我使用HTML,JavaScript和CSS

谢谢

最佳答案

请尝试以下解决方案。



.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()">&#9776; open</span>

09-26 22:42