使(JavaScript-toggable) DIV关闭(CSS: 'display: none')当点

Make (JavaScript-toggable) DIV close (CSS: 'display: none') when CLICKING OUTSIDE of it as well?

本文关键字:none 当点 display CSS JavaScript-toggable DIV 关闭      更新时间:2023-09-26

我有一个div (box),在点击另一个div (text)时在' display: block '和' display: none '之间切换(使用JavaScript)。该框中还有一个关闭选项(' display: none ')。

在该框中还有其他div(例如Google Translate下拉菜单),我希望在不关闭框的情况下可以点击。

  • 那么,当单击该框的外部时,我如何使框关闭(与CSS: ' display: none ') ?我如何在下面的代码实现?

  • 我的设置的简化和演示:JSFiddle

JavaScript和HTML(清除多余的数据):

<div id="toggle-container">
   <div id="toggle-text"> <p class="notranslate"><a href="#"
   onclick="toggle_visibility('toggle-box');">TOGGLE BOX</a></p>
   <script type="text/javascript">
       function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
       e.style.display = 'none';
       else
       e.style.display = 'block';
       }
   </script>
     <div id="toggle-box">  
         <div id="box-content">..with other divs...</div>
       <div id="translate-box-close">
               <a onclick="document.getElementById('toggle-box')
               .style.display='none';return false;" href="">CLOSE BOX</a></div>
     </div>
   </div>  
</div>
CSS

(清除过多的数据):

#toggle-container { 
}
#toggle-text { 
}
#toggle-box { 
 position: ABSOLUTE;
 display: NONE;
}
#box-content {
}

试试这个:

添加onclick="toggle_visibility('toggle-box');"<html>标签。

或在JavaScript内部:

 $('html').click(function() {
     toggle_visibility('toggle-box');
 });