event是ie自帶的一個對象,而ff中不存在該對象,只能透過傳遞參數的方式來模擬event
另外ie中使用srcElement去取得事件觸發來源,ff下則使用target。因此使用這兩個物件時需要做相關的瀏覽器相容。
複製代碼代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>srcElement --//www.VeVB.COm/</title>
<script type="text/javascript">
<!--
function Click(event){
event = event? event: window.event
var obj = event.srcElement ? event.srcElement:event.target;
alert(obj.tagName);
}
//-->
</script>
</head>
<body>
<button id="btn" onclick="Click(event)">點選</button>
</body>
</html>
查看運行結果
綜合上節attachEvent與addEventListener。
複製代碼代碼如下:
<script type="text/javascript">
<!
function Click(event){
event = event? event: window.event;
var obj = event.srcElement ? event.srcElement:event.target;
alert("eventObj.tabName:" + obj.tagName);
}
var oBtnNew;
window.onload=function(){
oBtnNew=document.getElementById("btnNew");
if(window.attachEvent){
oBtnNew.attachEvent("onclick",hanlder);
oBtnNew.attachEvent("onmouseover",hanlder);
}else{
oBtnNew.addEventListener("click",hanlder,false);
oBtnNew.addEventListener("mouseover",hanlder,false);
}
/*或採用下面試
oBtnNew.onclick=hanlder;
oBtnNew.onmouseover=hanlder;*/
}
function hanlder(event){
event=event?event:window.event;
if(event.type=="click")
oBtnNew.innerHTML="發生了onclick事件";
else if(event.type=="mouseover")
oBtnNew.innerHTML="發生了onmouseover事件";
}
//>
</script>
</head>
<body>
<button id="btn" onclick="Click(event)">點選</button>
<button id="btnNew">新增事件點擊</button>