首页 > 解决方案 > 如何使屏幕上的所有内容变暗,除了您单击汉堡按钮的 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";
    }

标签: javascripthtml

解决方案


当单击按钮时,这个基本示例将在页面前面放置一个阻挡封面。正如我在评论中所说,它通过使用元素classList并在 div 上切换一个作为封面的类来发挥作用。

在这个示例中,盖子在 5 秒后被移除;实际上,您会在某些事件后移除封面,例如当用户在您的 sidenav 中做出另一个选择时,或者,如果从 sidenav 导航到另一个页面,您不必移除封面,因为新的目标页面不会一开始就放上来。

要获得更精确的控制,您可以使用addremove代替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>


推荐阅读