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;
    width: 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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM