jquery - 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">×</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">☰ open</span>
</div>
I have tried setting the z-index for the body real high but it doesn't work.
解决方案
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.
推荐阅读
- node.js - 部署到 Netify 成功后的超时任务
- python - 访问随机 CV 搜索中所有迭代的所有结果
- python - 如何将张量连接到批次中的 keras 层(不指定批次大小)?
- java - Java 9 模块 VScode
- python - 如何按列对numpy数组进行排序?
- react-native - 中继条件片段导致错误
- ssh - 使用 2FA 时,如何测试我是否已通过 SSH 成功连接到 IPython 内核的所有*五个*通道(shell、iopub、hb、stdin、控制)?
- bash - 将 Bash 中的变量作为参数扩展为 rsync
- html - 可以禁用外部服务 iframe 内的链接(或任何可点击元素),但允许滚动内部内容?
- javascript - 使用导入“无法在初始化之前访问 ModuleName”