如何在侧边栏显示时禁用背景,并且单击侧边栏以外的任何地方都将关闭侧边栏。

3

我正在为我的网站制作侧边栏。

  1. 当侧边栏出现(点击showRight)时,我希望禁用背景内容,以便用户不能在菜单外执行任何操作。
  2. 当用户点击背景时,侧边栏将消失,然后他们将再次访问背景内容。目前,我在点击隐藏按钮时关闭侧边栏。

有人能帮帮我吗?

这是我的代码:

<html>
<head>
  <style>
    .cbp-spmenu {
      background: #fff;
      position: fixed;
    }

    .cbp-spmenu-vertical {
      width: 400px;
      height: 100%;
      top: 0;
      z-index: 1000;
    }

    .cbp-spmenu-right {
      right: -400px;
    }

    .cbp-spmenu, #cbp-spmenu-push {
      -webkit-transition: all 0.3s ease;
      -moz-transition: all 0.3s ease;
      transition: all 0.3s ease;
    }
  </style>
</head>
<body>
  <div id="menu">
    <span class="cbp-spmenu cbp-spmenu-vertical cbp-spmenu-right" id="cbp-spmenu-s1">
      <h4>Avinash</h4>
    </span>
  </div>
  <div id="content">
    <section id="about">
      <button id="showRight">Show</button>
      <button id="showRight2">Hide</button>
    </section>
    <script>
      var menuRight = document.getElementById( 'cbp-spmenu-s1' ),
          showRight = document.getElementById( 'showRight' ),
          showRight2 = document.getElementById( 'showRight2' ),
          content = document.getElementById( 'avi' ),
          menu = document.getElementById( 'menu' ),
          body = document.body;

      showRight.onclick = function() {
        classie.add(this,"active");
        menuRight.style.right = '0px';
        content.style.opacity = '0.5';
        body.style.display = 'block';
      };

      showRight2.onclick = function() {
        if (classie.has(showRight,"active")) {
          menuRight.style.right = '-400px';
          classie.remove(showRight,"active");
          content.style.opacity = '1';
        } 
      };
    </script>
  </div>
</body>
</html>
2个回答

1
在我看来,您可以创建一个覆盖整个站点除侧边栏外的div。将此div放置在body标签之后,如下所示:
<div class="overlay"></div>

在你的 CSS 中:
body{
  overflow-y: hidden;
}

.overlay{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 5000px;
  z-index: -1;
}

然后使用你的javascript将该div的z-index值更改为9999或其他覆盖所有内容的值。更新:在css中将你的侧边栏z-index设置为比这个新值更高的值。如果你没有得到更好的答案,考虑这个方法可能不是最理想的。

1
z-index 需要位于侧边栏和内容之间,而不是覆盖在一切上面 :p 除此之外,这个解决方案就可以了。 - Frederik Witte
由于我的侧边栏具有 z-index:1000,我通过JavaScript将 div overlayz-index 更改为 999,但现在侧边栏没有出现。overlay.onclick = function(){ overlay.style.z-index = "999"; } 但是当我删除 onclick 的 JavaScript 函数时,它正常显示。 - tenstormavi

0

你应该添加覆盖块。

<div class="overlay"></div>

.overlay {
  position: fixed;
  width: 100%;
  height: 100%;
  z-index: 999; /* sidebar must have z-index > 999 */
  background: white;
  opacity: 0; /* or background set to rgba(255, 255, 255, 0); */
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接