| 特性 | onmousedown | onclick |
|---|---|---|
| 觸發時機 | 鼠標按鍵**按下**瞬間 | 鼠標按下**並釋放**,且在**同一元素**上 |
| 事件順序 | 第一步 | 第三步(mousedown → mouseup → click) |
| 取消條件 | 無(按下即觸發) | 按下後移出元素再釋放,不觸發 click |
| 默認行為關聯 | 文本選擇、拖拽開始、焦點獲取 | 鏈接跳轉、表單提交、按鈕點擊 |
| event.button | 0=左鍵, 1=中鍵, 2=右鍵(均觸發) | 通常僅左鍵觸發 |
onclick = onmousedown (同元素) + onmouseup (同元素) + 目標檢查
場景:點擊 `` 鏈接,跳轉前必須發送統計埋點/保存草稿/記錄日誌(異步請求)。
<a href="next.html" onclick="sendLog(); return true;">跳轉</a>
function sendLog() {
// 異步請求,不等待直接返回
fetch('/log', { method: 'POST', body: 'click' });
// 瀏覽器立即跳轉,請求可能被取消
}
問題:瀏覽器不會等待異步操作完成就跳轉,請求大概率失敗。
<a href="next.html" id="link">跳轉</a>
document.getElementById('link').addEventListener('click', async function(e) {
e.preventDefault(); // 阻止默認跳轉
try {
await fetch('/log', { method: 'POST', body: 'click' }); // 等待完成
} catch (err) {
console.error(err);
}
window.location.href = this.href; // 手動跳轉
});
<a href="next.html"
onmousedown="sendLogEarly()"
onclick="return true;">跳轉</a>
function sendLogEarly() {
// 在 mousedown 時發起,比 onclick 早 ~100-200ms
navigator.sendBeacon('/log', 'click'); // 最佳:瀏覽器保證發送
// 或 fetch(..., { keepalive: true }) // 也可在卸載階段發送
}
關鍵 API:`navigator.sendBeacon(url, data)` —— 專為頁面卸載前發送數據設計,瀏覽器會可靠彈性發送,不阻塞跳轉,無需 await。
window.addEventListener('pagehide', function(e) {
if (e.persisted) return; // 彈出緩存不重複發
navigator.sendBeacon('/log', 'page_unload');
});
| 場景 | 推薦事件 | 理由 |
|---|---|---|
| 拖拽開始 | mousedown | 需即時響應,捕獲初始座標 |
| 右鍵菜單 | contextmenu | 專門事件,可 preventDefault 禁用默認 |
| 文本選擇檢測 | mouseup + getSelection() | 選擇結束時檢測 |
| 按鈕點擊反饋 | mousedown (按下態) + mouseup/click (恢復) | 視覺即時反饋 |
| 防止雙擊選中文本 | mousedown -> preventDefault() | 阻止瀏覽器默認選中行為 |
| 長按檢測 | mousedown + setTimeout + mouseup 清除 | 按下計時,釋放取消 |
element.addEventListener('mousedown', function(e) {
console.log('button:', e.button); // 0左 1中 2右
console.log('buttons:', e.buttons); // 位掩碼:1左 2右 4中(同時按下可組合)
console.log('which:', e.which); // 非標準,同 button+1
});
element.addEventListener('click', function(e) {
console.log('button:', e.button); // 始終為 0 (左鍵)
console.log('detail:', e.detail); // 點擊次數:1單擊 2雙擊 3三擊
});
`onmousedown` 早、`onclick` 晚且有條件。需要「搶時間」執行異步任務(埋點、保存)時,優先用 `mousedown` + `navigator.sendBeacon()`;需要確認用戶「完整點擊意圖」時用 `click`。現代開發推薦 `addEventListener` + `async/await` 或 `sendBeacon`,避免內聯事件屬性。