1 function stopBubble(e) { 2 //如果提供了事件對象,則這是一個非IE瀏覽器 3 if ( e && e.stopPropagation ) 4 //因此它支持W3C的stopPropagation()方法 5 e.stopPropagation(); 6 else7 //否則,我們需要使用IE的方式來取消事件冒泡 8 window.event.cancelBubble = true; 9 }
2.當按鍵后,不希望按鍵繼續傳遞給如HTML文本框對象時,可以取消返回值.即停止默認事件默認行為.
1 //阻止瀏覽器的默認行為 2 function stopDefault( e ) { 3 //阻止默認瀏覽器動作(W3C) 4 if ( e && e.preventDefault ) 5 e.preventDefault(); 6 //IE中阻止函數器默認動作的方式 7 else 8 window.event.returnValue = false; 9 return false; 10 }
那么通過下面的一段代碼我們來看下函數一的效果:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 4 <head> 5 <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> 6 <title>效果測試</title> 7 <script language="javascript" type="text/javascript" src="jquery-1.4.2.js?1.1.11"></script> 8 <script language="javascript" type="text/javascript"> 9 $(document).ready(function()10 {11 $('div.c1').click(function(e){alert('單擊了div');});12 $('div.c2').click(function(e){alert('單擊了div');stopBubble(e);});13 $(document).click(function(e){alert('單擊了document');});14 $('#txt1').val('123');15 $('#txt1').click(function(e){stopBubble(e);});16 $('#txt1').keydown(function(e){stopDefault(e);alert('你按下了鍵值'+e.keyCode); });17 })18 19 function stopBubble(e) { 20 //如果提供了事件對象,則這是一個非IE瀏覽器 21 if ( e && e.stopPropagation ) 22 //因此它支持W3C的stopPropagation()方法 23 e.stopPropagation(); 24 else 25 //否則,我們需要使用IE的方式來取消事件冒泡 26 window.event.cancelBubble = true; 27 } 28 //阻止瀏覽器的默認行為 29 function stopDefault( e ) { 30 //阻止默認瀏覽器動作(W3C) 31 if ( e && e.preventDefault ) 32 e.preventDefault(); 33 //IE中阻止函數器默認動作的方式 34 else 35 window.event.returnValue = false; 36 return false; 37 }38 </script>39 <style type="text/css">40 body{41 font-size:14px;42 }43 }44 .c1{45 font-family:"Arial Unicode MS"46 }47 .c2{48 font-family:helvetica,simsun,arial,clean49 }50 </style>51 </head>52 53 <body>54 55 <div class="c1">測試的文字,這里是樣式C1,單擊以冒泡的形式觸發事件.</div><hr/>56 57 <div class="c2">測試的文字,這里是樣式C2,單擊以捕獲的形式觸發事件.</div><hr/>58 59 <div><input id="txt1" name="Text1" type="text" /></div><hr/>60 61 </body>62 </html>
停止冒泡通用方法:
function stopBubble(e) { //如果提供了事件對象,是非IE瀏覽器 if ( e && e.stopPropagation ) //使用W3C的stopPropagation()方法 e.stopPropagation(); else //使用IE的cancelBubble = true來取消事件冒泡 window.event.cancelBubble = true; }
阻止瀏覽器默認行為-通用方法
//阻止瀏覽器的默認行為
function stopDefault( e ) { //阻止默認瀏覽器動作(W3C) if ( e && e.preventDefault ) e.preventDefault(); //IE中阻止函數器默認動作的方式 else window.event.returnValue = false; return false; }
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com