js实现的点击div区域外隐藏div区域

首先看下JS的事件模型,JS事件模型为向上冒泡,如onclick事件在某一DOM元素被触发后,事件将跟随节点向上传播,直到有click事件绑定在某一父节点上,如果没有将直至文档的根。

阻止冒泡:1、stopPropagation()对于非IE浏览器。2、cancelBubble属性为true,对于IE浏览器,

而Jquery已经有兼容浏览器的方法,event.stopImmediatePropagation();

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>无标题文档</title>
  <script type="text/javascript" src="js/jquery-1.10.2.js"></script>
  <script type="text/javascript">
    window.onload = function () {
      document.onclick = function (e) {
        $("#info").hide();
        $("#MoreContent").hide();
      }
      $('#openUserInfo').bind("click", function (e) {
        if ($("#info").css("display") == "none") {
          $("#info").show();
        } else {
          $("#info").hide();
        }
        e = e || event; stopFunc(e);
      });

      //阻止向上传递事件
      $('#info').bind("click", function (e) {
        e = e || event; stopFunc(e);
      });
    }

    function stopFunc(e) {
      e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
    }
</script>
<style type="text/css">
  #info {
    display: none;
     180px;
    height: 300px;
    background-color: gray;
  }
</style>
</head>

<body>
 <div class="top_menu">
  <div class="right_div">
    <a id="openUserInfo" href="javascript:void(0)">
    <div class="head_portrait">设置</div>
      </a>
    </div>
  </div>
  <div id="info">
    <div>
      <ul>
      <a role="menuitem" tabindex="-1" href="http://www.baidu.com">
        <li>
          &nbsp;&nbsp;浮层,点击这个浮层以外的区域,都可以隐藏这个浮层
          最主要的是点这个div里面的链接,div照样不隐藏
        </li>
      </a>
      <a role="menuitem" tabindex="-1" href="http://www.baidu.com">
        <li>
          &nbsp;&nbsp;百度
        </li>
      </a>
      <a href="/Login/LoginOut" onclick="return confirm('确定退出统一?');">
        <li>
          &nbsp;&nbsp;退出
        </li>
      </a>
    </ul>
  </div>
</div>
</body>
</html>

 

原文地址:https://www.cnblogs.com/liaoshiqi/p/5972325.html