javascript阻止事件冒泡和瀏覽器的預設行為,javascript冒泡

來源:互聯網
上載者:User

javascript阻止事件冒泡和瀏覽器的預設行為,javascript冒泡

1.阻止事件冒泡,使成為捕獲型事件觸發機制.

function stopBubble(e) { //如果提供了事件對象,則這是一個非IE瀏覽器 if ( e && e.stopPropagation )   //因此它支援W3C的stopPropagation()方法   e.stopPropagation(); else  //否則,我們需要使用IE的方式來取消事件冒泡   window.event.cancelBubble = true; }

2.當按鍵後,不希望按鍵繼續傳遞給如HTML文字框對象時,可以取消傳回值.即停止預設事件預設行為.

 //阻止瀏覽器的預設行為 function stopDefault( e ) {   //阻止預設瀏覽器動作(W3C)   if ( e && e.preventDefault )     e.preventDefault();   //IE中阻止函數器預設動作的方式   else    window.event.returnValue = false;   return false; }
<!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 content="text/html; charset=utf-8" http-equiv="Content-Type" /><title>效果測試</title><script language="javascript" type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script><script language="javascript" type="text/javascript">$(document).ready(function(){$('div.c1').click(function(e){alert('單擊了div');});$('div.c2').click(function(e){alert('單擊了div');stopBubble(e);});$(document).click(function(e){alert('單擊了document');});$('#txt1').val('123');$('#txt1').click(function(e){stopBubble(e);});$('#txt1').keydown(function(e){stopDefault(e);alert('你按下了索引值'+e.keyCode); });})function stopBubble(e) { //如果提供了事件對象,則這是一個非IE瀏覽器   if ( e && e.stopPropagation )   //因此它支援W3C的stopPropagation()方法   e.stopPropagation();    else   //否則,我們需要使用IE的方式來取消事件冒泡   window.event.cancelBubble = true; } //阻止瀏覽器的預設行為 function stopDefault( e ) {   //阻止預設瀏覽器動作(W3C)   if ( e && e.preventDefault )     e.preventDefault();   //IE中阻止函數器預設動作的方式   else     window.event.returnValue = false;   return false; }</script><style type="text/css">body{font-size:14px;  }}.c1{  font-family:"Arial Unicode MS"  }.c2{  font-family:helvetica,simsun,arial,clean  }</style></head><body><div class="c1">測試的文字,這裡是樣式C1,單擊以冒泡的形式觸發事件.</div><hr/><div class="c2">測試的文字,這裡是樣式C2,單擊以捕獲的形式觸發事件.</div><hr/><div><input id="txt1" name="Text1" type="text" /></div><hr/></body></html>

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的協助,同時也希望多多支援幫客之家!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.