?
2、有關?event?和?window.event
在IE/Opera中,是window.event,而在Firefox中,是event
而事件的對象,在IE中是window.event.srcElement,在Firefox中是event.target,而在Opera中則兩者都支持。
我們還是用例子來說明。
//***********************************
<HTML>
<HEAD>
<TITLE>?event的跨瀏覽器測試 </TITLE>
<SCRIPT?LANGUAGE="JavaScript">
<!--
//Firefox中在寫關于event的函數的時候,必須把event對象作為參數傳遞給函數,這樣才能使用event對象
functiondoTestEvent( evt )
{
?
//如果是IE/Opera,我們就用 srcElement 來獲取觸發事件的對象
? //如果是Firefox,我們就用 target 來獲取觸發事件的對象
? varsrc=evt.srcElement?evt.srcElement:evt.target;
? alert( src.value );
}
//-->
</script>
</head>
<body>
<form?name="frmtest">
<input?type="button"?value="event?測試"?onclick="doTestEvent(event);"?name="bttest">
</form>
</body>
</html>
//***********************************
這里順便說一下判斷鼠標按鍵的問題。
在?IE?里面
左鍵是?window.event.button=1
右鍵是?window.event.button=2
中鍵是?window.event.button=4
沒有按鍵動作的時候?window.event.button=0
在?Firefox?里面
左鍵是?event.button=?0
右鍵是?event.button=2
中鍵是?event.button=?1
沒有按鍵動作的時候?event.button=0
在?Opera?7.23/7.54?里面
鼠標左鍵是?window.event.button=1
沒有按鍵動作的時候?window.event.button=?1
右鍵和中鍵無法獲取
而在?Opera?7.60/8.0?里面
鼠標左鍵是?window.event.button=0
沒有按鍵動作的時候?window.event.button=0
右鍵和中鍵無法獲取
下面我們寫一個能在?IE4.01+/Firefox?0.9+/Opera?7.23+?環境中均能運行正常的小程序,功能是用鼠標拖動層。
//***********************************
<HTML>
<HEAD>
<TITLE>?可用鼠標拖動的層?</TITLE>
<SCRIPT?LANGUAGE="JavaScript">
<!--
varmoving=false;
varinitX? =0;
varinitY? =0;
//*******************
// 獲取觸發事件的對象
//*******************
functionfindSrc(evt)
{
? return( evt.target?evt.target:evt.srcElement );
}
functionstart(evt)
{
??? //按下鼠標左鍵才允許移動
??? //evt.button == 1 IE/Opera 7.23/7.54
??? //evt.button == 0 Firefox/Opera 7.6+
??? if ( evt.button==1||evt.button==0)
??? {
??????? moving=true;
??????? initX? =evt.offsetX?evt.offsetX:evt.layerX;
??????? initY? =evt.offsetY?evt.offsetY:evt.layerY;
??????? findSrc( evt ).style.cursor= "move";
??????? window.status= "開始(button=" +evt.button+ ")";
??? } else {
???????
stop( evt );
??? }
}
functionstop( evt )
{
??? moving=false;
??? findSrc(
evt ).style.cursor= "";
??? window.status= "結束(button=" +evt.button+ ")";
}
functionmove(evt)
{
??? //按下鼠標左鍵才允許移動
??? //evt.button == 1
IE/Opera 7.23/7.54
??? //evt.button == 0
Firefox/Opera 7.6+
??? if (moving&& ( evt.button==1||evt.button==0 ))
??? {
??????? varintx=document.body.scrollLeft+evt.clientX; //獲取當前鼠標位置的X坐標
??????? varinty=document.body.scrollTop+evt.clientY; //獲取當前鼠標位置的Y坐標
??????? vardiv=findSrc( evt );
??????? div.style.top=inty-initY;
??????? div.style.left=intx-initX;
??????? window.status= "X=" +intx+ "
Y=" +inty+ " button=" +evt.button;
??? } else {
??????? window.status= "已停止(button=" +evt.button+ ")";
??? }
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<div?id="mdiv"
?????style="position:?absolute;?width:300px;?height:?200px;?background-color:?#FFFFE1;"
?????onmousedown="start(?event?);"
?????onmouseup="stop(?event?);"
?????onmouseout="stop(?event?);"
?????onmousemove="move(?event?);"></div>
//***********************************