event 物件是 window 物件的屬性。事件發生時會同時產生 event 物件,事件結束後它便消失。取得方式在兩大陣營中不同:
IE:window.event // 取得 event 物件
DOM:arguments[0] // 或事件處理函數的第一個參數
clientX:事件發生時滑鼠指標在客戶區(不含工具列、捲軸等)的 X 座標。clientY:滑鼠指標在客戶區的 Y 座標。keyCode:對 keypress 事件代表按下的按鍵 Unicode 字元;對 keydown/keyup 則代表按鍵的數值碼。offsetX:滑鼠指標相對於引發事件之元素的 X 座標。offsetY:滑鼠指標相對於引發事件之元素的 Y 座標。srcElement:導致事件發生的元素。clientX/clientY:客戶區座標。pageX/pageY:滑鼠指標相對於整個頁面的座標。stopPropagation():呼叫後可阻止事件進一步傳播(停止冒泡)。target:觸發事件的元素或物件。type:事件名稱。相同點:
不同點:
// 1. 取得事件目標
IE :var oTarget = oEvent.srcElement;
DOM:var oTarget = oEvent.target;
// 2. 取得字元碼
IE :var iCharCode = oEvent.keyCode;
DOM:var iCharCode = oEvent.charCode;
// 3. 阻止預設行為
IE :oEvent.returnValue = false;
DOM:oEvent.preventDefault();
// 4. 終止冒泡
IE :oEvent.cancelBubble = true;
DOM:oEvent.stopPropagation();
onmouseover 滑鼠移入
onmouseout 滑鼠移出
onmousedown 按下滑鼠
onmouseup 抬起滑鼠
onclick 點擊左鍵
ondblclick 雙擊左鍵
onkeydown 在鍵盤上按下某個按鍵
onkeyup 釋放按下的按鍵
keypress 持續按住按鍵不放
onload 頁面載入時
onunload 頁面卸載時
abort 使用者中止載入,且內容尚未完全載入時
error JavaScript 發生錯誤時
select 在 input 或 textarea 中選取字元時
change input/textarea 失去焦點,或 select 選項變更時
submit 表單被提交時
reset 表單被重置時
resize 視窗或框架尺寸調整時
scroll 使用者捲動頁面或有捲軸時
focus 取得焦點時
blur 失去焦點時
1. 兩種傳播階段
冒泡型:<input type="button"> 被點擊時,順序為 input → body → html → document → window,由下往上。IE 只支援冒泡。
捕獲型:順序為 window → document → html → body → input,由上往下。經 ECMA 標準化後,其他瀏覽器兩種都支援,且捕獲先發生。
2. 傳統的三種寫法
<!-- 寫法一:直接在標籤上寫 -->
<input type="button" onclick="alert('helloworld!' )">
<!-- 寫法二:呼叫具名函數 -->
<input type="button" onclick="name1()">
<script>
function name1() { alert('helloworld!'); }
</script>
<!-- 寫法三:以匿名函數綁定 -->
<input type="button" id="input1">
<script>
var button1 = document.getElementById("input1");
button1.onclick = function () {
alert('helloworld!');
};
</script>
3. 現代的寫法
<!-- IE 的作法 -->
<input type="button" id="input1">
<script>
function fnClick() {
alert("我被點擊了");
}
var oInput = document.getElementById("input1");
oInput.attachEvent("onclick", fnClick); // 新增事件
oInput.detachEvent("onclick", fnClick); // 移除事件
</script>
<!-- 標準 DOM 的作法 -->
<input type="button" id="input1">
<script>
function fnClick() {
alert("我被點擊了");
}
var oInput = document.getElementById("input1");
oInput.addEventListener("click", fnClick, true); // 新增事件
oInput.removeEventListener("click", fnClick); // 移除事件
</script>
<!-- 同時相容 IE 與 DOM -->
<input type="button" id="input1">
<script>
var fnClick1 = function () { alert("我被點擊了"); };
var fnClick2 = function () { alert("我被點擊了"); };
var oInput = document.getElementById("input1");
if (document.attachEvent) {
oInput.attachEvent("onclick", fnClick1);
oInput.attachEvent("onclick", fnClick2);
} else if (document.addEventListener) {
oInput.addEventListener("click", fnClick1, true);
oInput.addEventListener("click", fnClick2, true);
}
</script>
這個「先檢測 API 再分流」的寫法就是特徵檢測(feature detection)的典型應用,比直接嗅探瀏覽器型別更可靠。