日期:2014-05-16  浏览次数:20342 次

好好学一遍JavaScript 笔记(十一)——事件的类型

一事件的类型:

    根据触发事件的事物和事件发生的对象,可将浏览器中发生的事件分成几个类型。DOM标准定义了以下几组事件:
    
  •     鼠标事件:用户使用鼠标操作时触发;
  •     键盘事件:用户敲击键盘、输入时触发;
  •     HTML事件:窗口发生变动或者发生特定的客户端-服务端交互时触发;
  •     突变事件:底层的DOM结构发生改变时触发。
    

1、鼠标事件

  •     click——用户点击鼠标左键时发生(如果右键也按下则不会发生)。如果焦点在按钮上、敲回车也会触发该事件。
  •     dblclick——用户双击鼠标左键时发生(如果右键也按下则不会发生)。
  •     mousedown——用户点击任意一个鼠标按钮时发生。
  •     mouseout——鼠标指针在某个元素上、且用户正要将其移出元素的边界时发生。
  •     mouseover——鼠标移出某个元素、到另一个元素上时发生。
  •     mouseup——用户松开任意一个按钮时发生。
  •     mousemove——鼠标在某个元素上时持续发生。
    
<html>
  <head>
    <title>事件类型</title>
	<script type="text/javascript">
		function testEvent(oEvent){
			var oText = document.getElementById("textId"); 
			oText.value += "\n"+oEvent.type;
		}
	</script>
  </head>
  <body>
  	<div style="width: 100px; height: 100px; background-color: red;"
  	onclick="testEvent(event);" ondblclick="testEvent(event);" onmouseover="testEvent(event);"  
	onmousedown="testEvent(event);" onmousemove="testEvent(event);"
  	onmouseout="testEvent(event);" onmouseup="testEvent(event);" >
  	</div>  
  	<br/>
    <textarea id="textId"  rows="30" cols="100"></textarea>
    <br/>
  </body>
</html>

    使用mouseover和mouseout事件是改变页面上某个东西的外观的一个和流行的方法、例如下面的img、这是个非常简单的技巧、但经常用到:
    <img src="image1.gif" onmouseover = "this.src='image2.gif'" onmouseout="this.src='image1.gif'"></img>
    

1.1事件的属性

每个鼠标事件都会给以下event对象的属性填入值:
  • 坐标属性(例如clientX和clientY等);
  • type属性(事件的类型);
  • target(DOM)或srcElement(IE)属性;
  • button属性(只在mousedown、mouseover、mouseout 、mousemove和mouseup事件中)。

<html>
  <head>
    <title>事件类型</title>
	<script type="text/javascript">
		function testEvent(oEvent){
			var oText = document.getElementById("textId"); 
			oText.value += "\n"+oEvent.type;
                        oText.value += "\n at("+oEvent.clientX+","+oEvent.clientY+") 客户端浏览器坐标 ";
			oText.value += "\n at("+oEvent.screenX+","+oEvent.screenY+") 屏幕坐标 ";
			oText.value += "\n button down is "+oEvent.button;
			var keys = [];
			if(oEvent.shiftKey){
				keys.push("Shift");
			}
			if(oEvent.ctrlKey){
				keys.push("Ctrl");
			}
			if(oEvent.altKey){
				keys.push("Alt");
			}
			oText.value += "\n keys down are " +keys;
		}
	</script>
  </head>
  <body>
  	<div style="width: 100px; height: 100px; background-color: red;"
  	onclick="testEvent(event);" ondblclick="testEvent(event);" onmouseover="testEvent(event);"  
	onmousedown="testEvent(event);" onmousemove="testEvent(event);"
  	onmouseout="testEvent(event);" onmouseup="testEvent(event);" >
  	</div>  
  	<br/>
    <textarea id="textId"  rows="30" cols="100"></textarea>
    <br/>
  </body>
</html>

这些属性都给出刚刚发生的鼠标事件的一些信息。

1.2顺序

    click事件触发前、会先发生mousedown事件、然后发生mouseup事件。类似的、要触发dblclick事件、在同一个目标上要按顺序发生以下事件:
  1.     mousedown;
  2.     mouseup;
  3.