当前位置:主页 > 网页前端 > JavaScript代码 >

Javascript Event(事件)的传播与冒泡

时间:2021-03-27 09:29:40 | 栏目:JavaScript代码 | 点击:

特性说明和原理图:

示例代码(ie8-示例不提供)

html代码

<body class="body" > 
 <div class="log"></div>
 <input type="text" id="inTxt" name="intxt" />
<div class="wrap">
 <div class="cont">
  <button type="button" class="button" id="btn">按钮</button>
  <select name="stopType" id="stopType">
    <option value="1">StopPropagation</option>
    <option value="2">cancelBubble</option>
  </select>
  <button type="button" class="button" id="btnReject">cont阻止捕获或冒泡</button>
 </div>
</div>
</body>

层级关系:body->wrap->cont->button,可以对照上面的原理

Js代码

$(function(){
    var $log = $('.log'), 
      $wrap = $('.wrap'),
      $cont = $('.cont'),
      $btn = document.getElementById('btn'),
      $stopType = $('#stopType'),
      $body = $('body'),
      $inTxt = $('#inTxt'),
      $btnReject = $('#btnReject');
    var ePhase = ["","捕获","目标","冒泡"]
    var setBorderColor = function( $dom, color, time,event){
      $dom = $($dom);
      $log.html($log.html() + $dom.attr('class') + '[' + ePhase[event.eventPhase] + ']' + '<br/>')
      var timeIndex = window.setTimeout(function(){   
      $dom.css({
        'borderColor': color,
        'borderWidth': '4px'
      });
      }, time);
    }  
    //捕获
    $body[0].addEventListener('click',function(event){ 
      $log.html($log.html() + "-------------------<br>");
      setBorderColor($body,'#0866ff ',0,event);
    },true);  
    $wrap[0].addEventListener('click',function(event){
      setBorderColor($wrap,'yellow',2000,event); 
    },true);
    $cont[0].addEventListener('click',function(event){
      event = event || window.event;
      if( $stopType.val() == '1' ){
        event.stopPropagation();
      }else{
        event.cancelBubble = true;
      }
      setBorderColor($cont,'green',1000,event);  
    },true); 
    $btn.addEventListener('click', function(event){ 
      setBorderColor($btn,'red',0,event);
    },true);
    $btnReject[0].addEventListener('click',function(event){ 
      setBorderColor($btnReject,'gray ',0,event);
    },true);
    //冒泡
    $body[0].addEventListener('click',function(event){
      setBorderColor($body,'#0866ff ',0,event);
    },false); 
    $wrap[0].addEventListener('click',function(event){
      setBorderColor($wrap,'yellow',2000,event); 
    },false); 
    $cont[0].addEventListener('click',function(event){
      setBorderColor($cont,'green',1000,event);  
    },false); 
    $btn.addEventListener('click', function(event){ 
      setBorderColor($btn,'red',0,event);
    },false);
    $btnReject[0].addEventListener('click',function(event){ 
      setBorderColor($btnReject,'gray ',0,event);
    },false);
    //阻止默认事件
    $inTxt.keypress(function(event){
      //event.preventDefault(); 
      window.event.returnValue = false;
      $body.append( String.fromCharCode( event.keyCode ));
    });
  });
  1. 实现一个完整的event流的Demo
  2. 在cont的捕获事件处有阻止事件传播的代码
  3. 阻止默认事件只用于验证

效果图

应用场景

您可能感兴趣的文章:

相关文章