javascript - 如何使屏幕上的所有内容变暗,除了您单击汉堡按钮的 sidenav 内容
问题描述
我想在单击并打开sidenav时使屏幕变暗,并可能冻结屏幕的其余部分,因此您无法向下滚动页面,而只能在sidenav上滚动,用于打开导航的我的js目前在下面我只有背景变暗,但页面上的所有链接仍然亮着并且可以点击,我怎样才能让一切变暗谢谢
// burger menu button with effects //
function openNav() {
document.getElementById("mySidenav").style.width = "280px";
document.body.style.background = "rgba(0,0,0,.8)";
document.getElementById("despair").style.opacity = "0.33";
document.getElementById("closebtn").style.marginLeft = "200px";
}
解决方案
当单击按钮时,这个基本示例将在页面前面放置一个阻挡封面。正如我在评论中所说,它通过使用元素classList并在 div 上切换一个作为封面的类来发挥作用。
在这个示例中,盖子在 5 秒后被移除;实际上,您会在某些事件后移除封面,例如当用户在您的 sidenav 中做出另一个选择时,或者,如果从 sidenav 导航到另一个页面,您不必移除封面,因为新的目标页面不会一开始就放上来。
要获得更精确的控制,您可以使用add和remove代替toggle。
如果您想让 sidenav 保持可用(不被阻止),您可以将其设置为比封面更高的 z-index。
const cover = document.getElementById('cover');
const blockit = document.getElementById('blockit');
blockit.addEventListener('click', function(event) {
event.preventDefault();
cover.classList.toggle('covering');
window.setTimeout(function() { cover.classList.toggle('covering'); }, 5000);
});
/*
The cover starts off not being displayed,
with a size of 0 x 0 pixels, and "behind"
the rest of the page (negative z-index)
*/
div#cover {
display: none;
position: fixed;
top: 0;
left: 0;
height: 0;
width: 0;
z-index: -1;
}
/*
When the "covering" class is added to the cover
it is displayed, has the size set to 100%, and
is raised to z-index 100, in front of the rest
of the page content.
*/
div#cover.covering {
display: block;
height: 100%;
width: 100%;
z-index: 100;
background-color: rgba(0, 0, 0, 30%);
}
<main>
<p>
This is a sample paragraph. It has a link to
<a href="https://stackoverflow.com/">Stackoverflow</a>
within the text of the paragraph. You want to make that link unclickable.
</p>
<button id="blockit">Block It</button>
</main>
<div id="cover"></div>
推荐阅读
- c - (sysmalloc: Assertion) 使用多个 MALLOCS 在 HEAP 中填充三重指针
- r - 嵌套的 for 循环不在 R 中运行
- java - 在spring data jpa中加入表
- hyperledger-fabric - 如何将两个不同的 Hyperledger Fabric 网络合并到具有两个不同通道的单个网络
- c - AIO 异步 I/O 中的回调
- javascript - 如何在快递服务器中获取发布请求参数?
- php - MySQL8 与 php7.3 和 Symfony 5 的连接不起作用
- azure-resource-manager - 有人知道 Azure 蓝图的未来吗?
- javascript - 如何在柏树中使用鼠标悬停选项
- c# - 在 json 字符串之前添加反斜杠并引发反序列化问题