1. 程式人生 > >windows.event物件介紹

windows.event物件介紹

1、event代表事件的狀態,例如觸發event物件的元素、滑鼠的位置及狀態、按下的鍵等等。event物件只在事件發生的過程中才有效。event的某些屬性只對特定的事件有意義。比如,fromElement 和 toElement 屬性只對 onmouseover 和 onmouseout 事件有意義。
2、屬性:
altKey, button, cancelBubble, clientX, clientY, ctrlKey, fromElement, keyCode, offsetX, offsetY, propertyName, returnValue, screenX, screenY, shiftKey, srcElement, srcFilter, toElement, type, x, y
3、屬性詳細說明:

屬性名 描述 說明
altKey 檢查alt鍵的狀態 當alt鍵按下時,值為True否則為False 只讀
shiftKey 檢查shift鍵的狀態 當shift鍵按下時,值為True否則為False 只讀
ctrlKey 檢查ctrl鍵的狀態 當ctrl鍵按下時,值為True否則為False 只讀
keyCode 檢測鍵盤事件相對應的內碼 可讀寫,可以是任何一個Unicode鍵盤內碼。如果沒有引發鍵盤事件,則該值為0
srcElement 返回觸發事件的元素 Object 只讀
x,y 滑鼠相對於當前瀏覽器的位置 px 只讀
clientX,clientY 滑鼠當前相對於網頁的位置 px 只讀
offsetX,offsetY 滑鼠當前相對於網頁中的某一區域的位置 px 只讀
screenX,screenY 相對於使用者顯示器的位置 px 只讀
returnValue 設定或檢查從事件中返回的值 true 事件中的值被返回 ,false 源物件上事件的預設操作被取消 可讀寫
button 檢查按下的滑鼠鍵 0 沒按鍵
1 按左鍵
2 按右鍵
3 按左右鍵
4 按中間鍵
5 按左鍵和中間鍵
6 按右鍵和中間鍵
7 按所有的鍵
僅用於onmousedown,onmouseup和onmousemove事件。對其他事件,不管滑鼠狀態如何,都返回0(比如onclick)
srcElement 檢測onmouseover和onmouseout事件發生時,滑鼠所離開的元素 Object 只讀
toElement 檢測onmouseover和onmouseout事件發生時,滑鼠所進入的元素 Object 只讀
type 返回事件名 返回沒有“on”作為字首的事件名,比如,onclick事件返回的type是click

例:(點選按鈕時顯示那幾個特殊鍵按下的狀態)

<input type="button" value="點選" onClick="showState()"/>
<script>
function show(){
 alert("altKey:"+window.event.altKey
  +"\nshiftKey:"+window.event.shiftKey
  +"\nctrlKey:"+window.event.ctrlKey);
}</script>

例:(按回車鍵讓下一元件得到焦點,相當按Tab鍵)

<input type="text" onKeyDown="nextBlur()"/>
<input type="text"/>
<script>
function nextBlur(){
 if(window.event.keyCode==13)//回車鍵的 code
  window.event.keyCode=9;//Tab鍵的code
}
</script>

例:(點選按鈕時顯示按鈕的name值)

<input type="button" value="閩" name="福建" onClick="show()"/>
<input type="button" value="贛" name="江西" onClick="show()"/>
<script>
function show(){
 alert(window.event.srcElement.name);
}
</script>

例如:遮蔽滑鼠右鍵、Ctrl+n、shift+F10、F5重新整理、退格鍵

function KeyDown(){ 
 //遮蔽滑鼠右鍵、Ctrl+N、Shift+F10、F5重新整理、退格鍵
  if ((window.event.altKey)&&
      ((window.event.keyCode==37)||   //遮蔽 Alt+ 方向鍵 ←
       (window.event.keyCode==39))){  //遮蔽 Alt+ 方向鍵 →
     event.returnValue=false;//防止使用ALT+方向鍵前進或後退網頁
  }
  if ((event.keyCode==8) ||      //遮蔽退格刪除鍵
      (event.keyCode==116)||   //遮蔽 F5 重新整理鍵
      (event.keyCode==112)||   //遮蔽 F1 重新整理鍵 bitsCN.com中國網管聯盟 
      (event.ctrlKey && event.keyCode==82)){ //Ctrl + R
     event.keyCode=0;
     event.returnValue=false;
  }
  if ((event.ctrlKey)&&(event.keyCode==78))   //遮蔽Ctrl+N
     event.returnValue=false;
  if ((event.shiftKey)&&(event.keyCode==121)) //遮蔽Shift+F10
     event.returnValue=false;
  if (window.event.srcElement.tagName == "A" && window.event.shiftKey) 
      window.event.returnValue = false;  //遮蔽 shift 加滑鼠左鍵新開一網頁
  if ((window.event.altKey)&&(window.event.keyCode==115)){ //遮蔽Alt+F4
      window.showModelessDialog("about:blank","","dialogWidth:1px;dialogHeight:1px");
      return false;}
}