事件对象:当事件发生时,浏览器自动建立该对象,并包含该事件的类型、鼠标坐标等。
事件对象的属性:格式: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中定义一个函数:
<script type=\"text/javascript\">
function clickHandler()
{
//do something
alert(\"button is clicked!\");
}
</script>
绑定事件的第一种方法:
<input type=\"button\" value=\"button1\" onclick=\"clickHandler();\"><br/>
绑定事件的第二种方法:
<input type=\"button\" id=\"button2\" value=\"button2\">
<script type=\"text/javascript\">
var v = document.getElementById(\"button2\");
v.onclick = clickHandler; //这里用函数名,不能加括号
</script>
其他实例
实例1:
<!DOCTYPE html>
<html>
<head>
<title>eventTest.html</title>
<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">
<meta http-equiv=\"description\" content=\"this is my page\">
<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">
<!--<link rel=\"stylesheet\" type=\"text/css\" href=\"./styles.css\">-->
<script>
function mOver(object) {
object.color = \"red\";
}
function mOut(object) {
object.color = \"blue\";
}
</script>
</head>
<body>
<font style=\"cursor:help\"
onclick=\"window.location.href=\'http://www.baidu.com\'\"
onmouseover=\"mOver(this)\" onmouseout=\"mOut(this)\">欢迎访问</font>
</body>
</html>
实例2:
<!DOCTYPE html>
<html>
<head>
<title>eventTest2.html</title>
<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">
<meta http-equiv=\"description\" content=\"this is my page\">
<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">
<!--<link rel=\"stylesheet\" type=\"text/css\" href=\"./styles.css\">-->
</head>
<body>
<script type=\"text/javascript\">
function getEvent(event) {
alert(\"事件类型: \" + event.type);
}
document.write(\"单击...\");
document.onmousedown = getEvent;
</script>
</body>
</html>