精细结构

目录

阻止网页元素向上冒泡

适用范围:做遮罩层时,点击最上层会连带点击到背景,用这个代码可以屏蔽元素冒泡
替代方案:绝对定位

<!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>
  <title> JavaScript阻止时间冒泡传递测试 </title>
  <style type="text/css">
      .outer_div{
         margin-top:20px;
         width:200px;
         height:150px;
         background: #ddd;
      }
      .inner_div{
         margin-top:20px;
         width:100px;
         height:50px;
         background: #eee;
      }
      </style>
 </head>
<body>
    <div id="parent" class="outer_div">
        <div id="child" class="inner_div">
            <input id="input_btn" type="button" value="按钮1" onclick="show('child button 1')" />
        </div>
        <div id="c2" class="inner_div">
            <input id="input_btn2" type="button" value="按钮2" onclick="show('child button 2')" />
        </div>
    </div>
</body>
<script type="text/javascript">
var parentNode = document.getElementById("parent");
parentNode.onclick = function(e) {
    if(e.target.id == "child") return;
    if(e.target.id == "input_btn") return;
    show(e.target.id);
};

function show(str) {
    alert(str);
}
</script>
</html>