2015-04-07 38 views
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> 

回答

1

在我看來,你可以創建一個覆蓋整個網站除了側邊欄

把你的身體標記之後這個div右像這樣一個div:

<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,該解決方案將做 –

+0

的確先生,答案已被更新。 –

+0

由於我的側邊欄有'z-index:1000',我正在通過javascript將'div overlay'的'z-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); */ 
}