一.事件对象的作用
1.可以获得和哪个按键结合
2.可以获得点击所在的位置
3.可以获得点击所对应的标签:
二.浏览器兼容:形参对象是针对于现代浏览器,IE浏览器不能通过形参无法通过形参获得对象,通过window.event来获得,即console.log(window.event)。
1.兼容操作方法:var ev=e || window.event; --此处为:或语法,返回为真的值。
–下为实例讲解:
<script type="text/javascript">
var wrap=document.getElementById('wrap');
wrap.onclick=function(e)
{
var ev=e || window.event; //或语法,返回为真的值
console.log(ev);
// 2.事件对象点击所在的位置
//clientX和clientY,针对于浏览器视窗而言
console.log("clientX:"+ev.clientX+" "+"clientY:"+ev.clientY);
//offsetX和offsetY相对于自身而言
console.log("offsetX:"+ev.offsetX+" "+"offsetY"+ev.offsetY);
//screenX和screenY相对于显示屏
console.log("screenX:"+ev.screenX+" "+"screenY:"+ev.screenY);
//3.点击所对应的标签
console.log(ev.target);
}
</script>
三:事件对象对应小练习:
–实现鼠标点击浏览器区域使标签区域跟着鼠标移动
<style type="text/css">
*{
margin:0;
padding:0;
}
#wrap{
width:100px;
height:100px;
background:green;
position:absolute;
}
</style>
</head>
<body>
<div id="wrap"></div>
<body>
</html>
<script type="text/javascript" src="getCss.js"></script>
<script type="text/javascript">
var wrap=document.getElementById('wrap');
var width=parseInt(getCss(wrap,"width"));
var height=parseInt(getCss(wrap,"height"));
window.onclick=function (e)
{
var ev=e||window.event;
var x=ev.offsetX;
var y=ev.offsetY;
//将x和y分别赋值给left和top
wrap.style.left=x-0.5*width+'px';
wrap.style.top=y-0.5*height+'px';
//回顾offsetWidth和offsetHeight分别是标签本身的宽和高,得到的是数字,用标签去调用。
}
</script>