js--事件对象的理解2

时间:2023-03-08 20:48:49

实例1:一串跟着鼠标飞舞的div

<!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>
<style>
div {width:10px; height:10px; background:red; position:absolute;}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>一串跟着鼠标飞舞的div </title>
<script>
window.onload=function ()
{
var aDiv=document.getElementsByTagName('div');
var i=0;
document.onmousemove=function (ev) //事件处理函数
{
var oEvent=ev||event; //兼容浏览器的事件对象的写法,event是IE的写法,火狐下 事件处理函数是可以有参数的。 || 若两边都为真,则出第一个;若一真一假,则输出假 for(i=aDiv.length-1;i>0;i--)
{
aDiv[i].style.left=aDiv[i-1].style.left;
aDiv[i].style.top=aDiv[i-1].style.top;
} aDiv[0].style.left=oEvent.clientX+'px'; //clientX 为浏览器的可视区坐标
aDiv[0].style.top=oEvent.clientY+'px';
};
};
</script>
</head> <body>
<div></div>
<div></div>
<div></div> <!--------------此处省略很多div-------->
</body>
</html>

  2.document是<!DOCTYPE 和html标签的父级

3.阻止事件冒泡:cancelBubble用于ie的阻止冒泡事件,event.stopPropagation()用于firefox和chrome等其他浏览器   。需要启用能力检测。

   //该函数的功能用来阻止冒泡,并兼容浏览器
function stopBubble(e){
if(e){
e.stopPropagation(); //因此他支持WW3C的stopPropagation()方法
}
else{
//否则,我们得使用IE的方式来取消事件冒泡
window.event.cancelBubble=true;
}
}