萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 滑鼠/鍵盤/視窗/表單事件完整速查表

事件分類總覽

類別事件觸發時機常用屬性/方法
滑鼠click點擊(mousedown + mouseup 同一元素)clientX/Y, button, detail
dblclick雙擊detail=2
mousedown按下滑鼠鍵button(0左/1中/2右)
mouseup釋放滑鼠鍵
mousemove滑鼠移動clientX/Y, movementX/Y
mouseover進入元素(冒泡)relatedTarget
mouseout離開元素(冒泡)relatedTarget
mouseenter進入元素(不冒泡)推薦搭配 mouseleave
mouseleave離開元素(不冒泡)
contextmenu右鍵選單e.preventDefault() 可禁用
wheel滾輪滾動deltaX/Y/Z, deltaMode
鍵盤keydown按鍵按下(持續觸發)key, code, keyCode(棄用), ctrlKey/shiftKey/altKey/metaKey
keyup按鍵釋放
keypress字元輸入(已棄用)charCode, 已移除標準,勿用
input輸入框值改變e.target.value, inputType, isComposing
視窗/文件load頁面/資源完全載入
DOMContentLoadedHTML 解析完成(不等 CSS/圖片)最早啟動 JS 的時機
beforeunload離開頁面前e.preventDefault(), e.returnValue='' 彈出確認
unload頁面卸載無法阻止,僅能做同步清理
resize視窗大小改變window.innerWidth/Height
scroll捲動window.scrollY, element.scrollTop
visibilitychange分頁顯示/隱藏切換document.hidden, document.visibilityState
online/offline網路狀態變化navigator.onLine
表單focus獲得焦點(不冒泡)focusin 冒泡版
blur失去焦點(不冒泡)focusout 冒泡版
change值變更並失去焦點(select、checkbox 即時)
input值即時改變inputType, data, isComposing
submit表單提交e.preventDefault() 阻止
reset表單重置
select文字被選取e.target.selectionStart/End
invalid驗證失敗HTML5 表單驗證
觸控/指標touchstart/move/end/cancel觸控螢幕touches, targetTouches, changedTouches
pointerdown/move/up/cancel統一滑鼠/觸控/筆pointerType, isPrimary, pressure
gotpointercapture/lostpointercapture捕獲指標setPointerCapture()
gesturestart/change/end多點手勢(Safari)rotation, scale
剪貼簿copy/cut/paste複製/剪下/貼上e.clipboardData.getData/setData
beforecopy/cut/paste執行前可修改/阻止
dragstart/drag/dragend/drop拖放e.dataTransfer

事件流:捕獲 → 目標 → 冒泡

// 捕獲階段監聽(第三參數 true 或 {capture: true})
element.addEventListener('click', handler, true);

// 冒泡階段(預設)
element.addEventListener('click', handler);

// 阻止傳播
e.stopPropagation();      // 停止冒泡/捕獲繼續
e.stopImmediatePropagation(); // 同元素其他監聽器也不執行

// 阻止預設行為
e.preventDefault();       // 如連結跳轉、表單提交、右鍵選單
// 回傳 false(僅內聯/屬性綁定有效)
// onclick="return false;"

事件物件常用屬性速查

屬性適用事件說明
target所有實際觸發事件的元素
currentTarget所有綁定監聽器的元素(this)
relatedTargetmouseover/out, focus/blur進入/離開的另一元素
clientX/Y滑鼠/觸控相對視窗座標
pageX/Y滑鼠相對文件座標(含捲動)
offsetX/Y滑鼠相對目標元素邊框座標
key鍵盤字元值("Enter", "a", "F1")
code鍵盤實體鍵位("KeyA", "Enter")
buttons滑鼠當前按下的鍵位元遮罩
detailclick/dblclick點擊次數
composedPath()所有事件傳播路徑陣列(含 Shadow DOM)

事件代理模式(效能最佳實踐)

// 不在每個 li 綁定,改在 ul 綁一個
document.getElementById('list').addEventListener('click', e => {
    const li = e.target.closest('li[data-id]');
    if (li) {
        const id = li.dataset.id;
        handleItemClick(id, e);
    }
});

function handleItemClick(id, e) {
    console.log('項目點擊:', id);
}

被動事件監聽器

// 告訴瀏覽器 handler 不會呼叫 preventDefault(),可優化滾動效能
element.addEventListener('touchmove', handler, {passive: true});
element.addEventListener('wheel', handler, {passive: true});

// 需要 preventDefault 時設 false
element.addEventListener('touchstart', handler, {passive: false});

自訂事件

// 建立並派發
const event = new CustomEvent('my-event', {
    detail: {userId: 123, action: 'login'},
    bubbles: true,
    cancelable: true
});
element.dispatchEvent(event);

// 監聽
element.addEventListener('my-event', e => {
    console.log(e.detail.userId); // 123
});
copyright © 萬盛學電腦網 all rights reserved