javascript阻止事件冒泡和浏览器的默认行为

出自:http://hi.baidu.com/wely_ton/blog/item/6b33ca1ae9d4d2dead6e753e.html
javascript阻止事件冒泡和浏览器的默认行为
就是说用Div框住flash  Div的鼠标事件不传递给Body

文中说的方法记录一下
/* ---------------------------
    功能:停止事件冒泡
    ---------------------------
*/
    
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 ;
    }


使用方法
// 监视用户何时把鼠标移到元素上,
     // 为该元素添加红色边框
    unionDom[i].onmouseover  =   function (e)  {
        
this .style.border  =  " 1px solid red " ;
        stopBubble( e );
    }
;
    
// 监视用户何时把鼠标移出元素,
     // 删除我们所添加的红色边框
    unionDom[i].onmouseout  =   function (e)  {
        
this .style.border  =  " 0px " ;
        stopBubble( e );
    }
;

uniconDom[i]是页面的一个html标记

实例二:

<!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 http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>demo</title>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="zh-cn" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<title>demo</title>
<meta name="Description" content="网页说明" />
<meta name="Keywords" content="网页关键字" />
<meta name="Robots" content="all" />
<meta name="Author" content="" />
<meta name="Copyright" content=" 版权所有 2009" />
<link href="css/global.css" rel="stylesheet" type="text/css" media="all" />
<script type="text/javascript">
//阻止事件冒泡后,你点击灰色盒子,整个过程只弹一次对话框了(注意与默认情况对比)
function showMsg(obj,evt)
{
alert(obj.id);
var e=(evt)?evt:window.event;
stopBubble(e);
}

//阻止事件冒泡函数
function stopBubble(e)
{
if(window.event){
window.event.cancelBubble=true;
}else{
e.stopPropagation();
}
}
</script>
</head>

<body>
<div id="wrap">
<div οnclick="showMsg(this,event)" id="outSide" style="width:100px; height:100px; color:#fff; background:#000; padding:50px">
outside
<div οnclick="showMsg(this,event)" id="inSide" style="width:100px; height:100px; color:red; background:#CCC">
inside
</div>
</div>
</div>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值