JavaScript学习笔记之JS事件对象
事件对象:当事件发生时,浏览器自动建立该对象,并包含该事件的类型、鼠标坐标等。
事件对象的属性:格式:event.属性。
一些说明:
event代表事件的状态,例如触发event对象的元素、鼠标的位置及状态、按下的键等等;
event对象只在事件发生的过程中才有效。
firefox里的event跟IE里的不同,IE里的是全局变量,随时可用;firefox里的要用参数引导才能用,是运行时的临时变量。
在IE/Opera中是window.event,在Firefox中是event;
而事件的对象,在IE中是window.event.srcElement,在Firefox中是event.target,Opera中两者都可用。
绑定事件
在JS中为某个对象(控件)绑定事件通常可以采取两种手段:
首先在head中定义一个函数:
<scripttype="text/javascript">
functionclickHandler()
{
//dosomething
alert("buttonisclicked!");
}
</script>
绑定事件的第一种方法:
<inputtype="button"value="button1"onclick="clickHandler();"><br/>
绑定事件的第二种方法:
<inputtype="button"id="button2"value="button2">
<scripttype="text/javascript">
varv=document.getElementById("button2");
v.onclick=clickHandler;//这里用函数名,不能加括号
</script>
其他实例
实例1:
<!DOCTYPEhtml>
<html>
<head>
<title>eventTest.html</title>
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="thisismypage">
<metahttp-equiv="content-type"content="text/html;charset=UTF-8">
<!--<linkrel="stylesheet"type="text/css"href="./styles.css">-->
<script>
functionmOver(object){
object.color="red";
}
functionmOut(object){
object.color="blue";
}
</script>
</head>
<body>
<fontstyle="cursor:help"
onclick="window.location.href='http://www.baidu.com'"
onmouseover="mOver(this)"onmouseout="mOut(this)">欢迎访问</font>
</body>
</html>
实例2:
<!DOCTYPEhtml>
<html>
<head>
<title>eventTest2.html</title>
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="thisismypage">
<metahttp-equiv="content-type"content="text/html;charset=UTF-8">
<!--<linkrel="stylesheet"type="text/css"href="./styles.css">-->
</head>
<body>
<scripttype="text/javascript">
functiongetEvent(event){
alert("事件类型:"+event.type);
}
document.write("单击...");
document.onmousedown=getEvent;
</script>
</body>
</html>