本篇文章给大家带来的内容是关于js中event事件对象是什么?js中event事件对象的介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
什么是事件对象?在触发dom上的某个事件时,会产生一个事件对象event。这个对象中包含着所有与事件有关的信息。
包括导致事件的元素,事件的类型以及其他与特定事件相关的信息。
比如:
鼠标操作导致的事件对象中,会包含鼠标位置的信息。
键盘操作导致的事件对象中,会包含按下的键有关的信息。
下面我们点击document看看event包含哪些东西。
event对象的兼容写法event事件对象不能兼容所有的浏览器,我们一般是采用下面这种方式进行兼容。
var oevent=ev || event;
如果参数不是ev而是event的时候,兼容方式也可以写成下面这种格式。
document.onclick=function(event){ var oevent=event || window.event; console.log(oevent);}
测试代码如下:
<!doctype html><html> <head> <title>event兼容测试</title> <script> window.onload=function(){ document.onclick=function(ev){ var oevent=ev || event; console.log(event); } } </script> </head> <body> </body></html>
event常用属性有哪些oevent.type;——获取绑定的事件类型,比如click,mouseover等
oevent.target;(在ie低版本中用event.srcelement)——返回触发事件的元素。比如[object htmlinputelement]指的是html里的input元素
oevent.currenttarget;(ie低版本中不存在)表示当前所绑定事件的元素,跟target的区别看下面
<!doctype html><html> <head> <title>event.target和event.currenttarget的区别</title> <script> window.onload=function(){ document.onclick=function(ev){ var oevent=ev || event; var ocurrentelement=oevent.target || oevent.srcelement; console.log(ocurrentelement); console.log(oevent.currenttarget); console.log(oevent.type); } } </script> </head> <body> <input id="btn1" type="button" value="事件处理程序"> </body></html>
oevent.stoppropagation()[ˌprɒpə'ɡeɪʃn];(在ie中用oevent.cancelbubble=false)//用于阻止事件冒泡
oevent.stopimmediatepropagation();//immediate[ɪˈmi:diət] //当一个元素绑定多个事件处理程序的时候,事件会按照顺序全部执行,如果不想让后面的事件处理程序执行,就在当前事件里加这个方法,就不执行后面的事件处理程序了。
oevent.preventdefault();(在ie低版本中用oevent.returnvalue=true)//阻止事件的默认行为,比如阻止a的href链接。
<!doctype html><html> <head> <title>仿select下拉框、阻止默认动作、阻止默认行为</title> <style> #p1{ width: 400px; height: 300px; background: #ccc; display: none; } </style> <script> window.onload=function(){ var obtn=document.getelementbyid(btn1); var op=document.getelementbyid(p1); var oa=document.getelementbyid(a1); obtn.onclick=function(event){ op.style.display=block; var oevent=event || window.event; if(oevent.stoppropagation){ oevent.stoppropagation(); }else{ oevent.cancelbubble=true;//ie,在新版的chrome中支持 } } oa.onclick=function(){ var oevent=event || window.event; if(oevent.preventdefault){ oevent.preventdefault(); }else{ oevent.returnvalue=false;//ie } } document.onclick=function(){ op.style.display=none; } } </script> </head> <body> <input id="btn1" type="button" value="显示"> <p id="p1"></p> <a href="http://www.baidu.com" id="a1">a链接</a> </body></html>
oevent.clientx;鼠标的横坐标。
oevent.clienty;鼠标的纵坐标。
相关推荐:
event对象及各种事件总结
javascript dom事件对象和ie事件对象实例详解
js获取事件源及触发该事件的对象_javascript技巧
以上就是js中event事件对象是什么?js中event事件对象的介绍的详细内容。