如何在显示侧边栏时禁用背景并单击除侧边栏之外的任何位置将关闭侧边栏

问题描述 投票:0回答:2

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

  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>
javascript jquery css sidebar
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 设置为高于此新值

可能并不理想,但如果您没有得到更好的答案,请考虑它。


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); */
}
© www.soinside.com 2019 - 2024. All rights reserved.