特性说明和原理图:
示例代码(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 ));
});
});
效果图
应用场景
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持亿速云!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。