首页 > 解决方案 > Overlay not covering NavBar

问题描述

When click on the open button, the side menu will display and I would the whole body to cover with the background-color that I set. The overlay does cover everything except the Menu bar. Is there a work around this? Thanks.

$(document).ready(function() {

  $("#openNav").click(function() {
    $("#mySidenav").css({
      'width': '20%'
    });
    $("body").css({
      'background-color': 'rgba(0, 0, 0, 0.5)',
      'z-index': ' 10000'
    });
  });


  $(".closebtn").click(function() {
    $("#mySidenav").css({
      'width': '0'
    });
    $("body").css({
      'background-color': 'rgba(0, 0, 0, 0)'
    });
  });

});
body {
  font-family: "Lato", sans-serif;
  /* background-color: rgba(0, 0, 0, 0.5); */
}

.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1000;
  top: 0;
  left: 0;
  background-color: white;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
  border-style: solid;
}

.sidenav a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.sidenav a:hover {
  color: #f1f1f1;
}

.sidenav .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>



<div id="mySidenav" class="sidenav">
  <a href="javascript:void(0)" class="closebtn">&times;</a>
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Clients</a>
  <a href="#">Contact</a>
</div>

<div style="width: 100%; text-align: right; background-color: white; height:100px; border-style: solid; poisition: relative" id="openNav">
  <span style="font-size:30px;cursor:pointer">&#9776; open</span>
</div>

I have tried setting the z-index for the body real high but it doesn't work.

标签: jquerycss

解决方案


Instead of trying to alter the body color, add a class to the body instead.

// open the menu
$("#openNav").click(function() {
    $("#mySidenav").css({
      'width': '20%'
    });
    $("body").addClass('menu-open');
  });
// close the menu
$(".closebtn").click(function() {
    $("#mySidenav").css({
      'width': '0'
    });
    $("body").removeClass('menu-open');
  });

Then add this to your css:

body.menu-open::after {
  content:'';
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

This creates an overlay to display on top of the body, but because of the z-index it will appear under the side menu.


推荐阅读