单击正文 HTML 时隐藏元素



我有这段代码,一切正常,我想让所有元素#内容1,#内容2..在点击正文时隐藏。我尝试使用 z 索引小于div 的身体进行设置,但没有帮助

    $(function() {
          $('#div1').click(function() {
            $('#content1, #content2, #content3').hide();
            $('#content1').show();
            /* other code ..*/
          });
          $('#div2').click(function() {
            $('#content1, #content2, #content3').hide();
            $('#content2').show();
            /* other code ..*/
          });
    });
 html,body{width:100%;height:100%;}
    #div1, #div2, #div3{
           overflow:hidden;
           float:left;
           width:40px;
           height:40px;
           background:red;
           margin:0 10px 0 0;
         }
         #content1, #content2, #content3{
         overflow:hidden;
         position:absolute;
         top:50px;
         background-color:#000;
         color:#fff;
         padding:2px 4px;
    }
<!doctype html>
<html>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <div id="div1">
          <div id="content1" style="display: none;">
            text1
          </div>
        </div>
        <div id="div2">
          <div id="content2" style="display: none;">
            text2
          </div>
        </div>
        <div id="div3">
          <div id="content3" style="display: none;">
            text3
          </div>
        </div>
</body>
</html> 

试试这个:

$(function() {
    var div1 = $("#div1");
    var div2 = $("#div2");
    var div3 = $("#div3");
    $("body").on("click", function (e) {
        if (div1.has(e.target).length || e.target == div1[0])
            return;
        else if (div2.has(e.target).length || e.target == div2[0])
            return;
        else if (div3.has(e.target).length || e.target == div3[0])
            return;
        $('#content1, #content2, #content3').hide();
    });
});
html,body{width:100%;height:100%;}
<div id="div1">
    <div id="content1">
     text1
    </div>
</div>
<div id="div2">
    <div id="content2">
     text2
    </div>
</div>
<div id="div3">
    <div id="content3">
     text3
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

你的代码和你所说的是两回事。所以:

  1. 如果您只想在单击body时隐藏所有#content元素,请按照 Jessika 的答案进行操作。

  2. 如果要
  3. 隐藏所有#content元素,除了单击的#content元素(即单击#content1时,要隐藏#content2#content3(,您可以简单地执行以下操作:

    $(function() {
        $('#div1').click(function() {
            $('#content2, #content3').hide();
            /* other code ..*/
        });
        $('#div2').click(function() {
            $('#content1, #content3').hide();
            /* other code ..*/
        });
        /* other code */
    });
    

    您可以保留内容并仅隐藏其他内容,而不是隐藏和显示内容。

最新更新