如何在侧边栏上打开整个屏幕半黑?

How can i make whole screen semi-black on sidebar open?

我用 cssjquery 构建了侧边栏。它工作正常,但我希望当侧边栏打开时,除了侧边栏之外的整个屏幕应该变成半黑或禁用。

这是我的作品 jsFiddle

如何在边栏打开时将整个屏幕设为半黑或禁用?

您可以在边栏上使用框阴影:

#sidebar{
 box-shadow:0 0 0 10000px rgba(0,0,0,.50);
}

这是黑色的,不透明度为 0.50。它设置为 10000px 以覆盖整个屏幕。

或者将 rgba(0,0,0,.50) 更改为纯色,如 #5a5a5a。

在你的情况下添加到你的 css:

#slide-out.visible:not(.close){
  box-shadow:0 0 0 10000px #666666;
}
  1. 在您的导航下方创建一个内容 div。类似于:

    <div id="maincontent" class=""> <p>Lorem.</p> </div>

  2. 添加一些样式使其具有最小高度等

    #maincontent { width: 100%; height: 100%; padding: 0; margin: 0; min-height: 400px; }

  3. 添加一些 JS,以便在单击导航菜单按钮时,它会打开和关闭此区域的新样式 class。

    $('#show-hide-menu').click(函数 () {

    if ($("div#maincontent").hasClass("overlayed")) { $("div#maincontent").removeClass("overlayed"); } 别的 { $("div#maincontent").addClass("overlayed"); } });

  4. 在CSS中定义覆盖class。

    .overlayed { background-color: rgba(0,0,0,.8); }

实现这一目标的一般概念相当简单:

  1. 修改 javascript 以在导航打开时向 body 添加一个 class(我称之为 nav-open。)
  2. 修改 CSS 以便当正文具有 class nav-open[=31= 时显示 "overlay" 元素(您已经有一个) ]
  3. 调整您的覆盖元素 CSS 以使其正确显示(出于某种原因,它上面有 opacity: 0,这意味着它 在那里 , 但 不可见 ).

这是相关的CSS:

#sidenav-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  width: 100vw;
  height: 100vh;
  // removed opacity: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 997;
  // set display to none by default
  display: none;
}

// when the body has the class nav-open, display the overlay
.nav-open #sidenav-overlay {
    display: block;
}

这是对您的 javascript 的相关更改:

// no-conflict-safe document ready function
jQuery(function($) {
    $('#show-hide-menu').click(function() {
       if ($('#slide-out').hasClass('visible')) {
         // $('#slide-out').removeClass('visible');
         $('#slide-out').toggleClass('close');
       } else {
         $('#slide-out').addClass('visible');
       }

        // check if the nav is "open"
        var open = !$('#slide-out').hasClass('close');

         // for simplicity, always first remove the nav-open from the body
         $('body').removeClass('nav-open');
         // if the nav is open, add the 'nav-open' class to the body
         if (open) {
           $('body').addClass('nav-open');
         }
     });

     // modify to use "on", is best-practice
     // $(document).click(function(e) {
     $(document).on('click', function(e) {
       var sidebar = $(".sidenav, #show-hide-menu");
       if (!sidebar.is(e.target) && sidebar.has(e.target).length === 0) {
         $('#slide-out').toggleClass('close');
         // be sure the nav-open class is removed when the sidebar is dismissed
         $('body').removeClass('nav-open');
       }
     });
});

这是您的 fiddle 的 link,根据您的需要进行了修改:http://jsfiddle.net/cale_b/hThGb/8849/