click事件

click 事件通常會在設備的按鈕(通常是滑鼠按鍵)點擊元素時執行。

冒泡傳遞
可取消
介面 MouseEvent
事件處理函式屬性 onclick

如果按下了一個元素內的按鈕,且在釋放按鈕之前將指正移到元素之外,則會在在包含這兩個元素的最具體的父級元素上觸發事件。

click事件會在mousedown (en-US)mouseup (en-US)事件之後觸發。

使用說明

傳遞給click事件處理函式的MouseEvent物件將其detail (en-US)屬性設置為點擊目標的次數。換句話說,detail在雙擊時為2,在三次點擊時為3,依此類推。該計數器在沒有任何點擊的情況下會在很短的時間間隔後重置;間隔時間的長短可能因瀏覽器和平台而異。間隔時間也很可能受到用戶偏好的影響;例如,無障礙選項可能會延長此間隔,以便更輕鬆地使用自適應介面執行多次點擊。

Internet Explorer

Internet Explorer 8 & 9 suffer from a bug where elements with a computed background-color of transparent (en-US) that are overlaid on top of other element(s) won't receive click events. Any click events will be fired at the underlying element(s) instead. See this live example for a demonstration.

Known workarounds for this bug:

Safari Mobile

Safari Mobile 7.0+ (and likely earlier versions too) suffers from a bug where click events aren't fired on elements that aren't typically interactive (e.g. <div>) and which also don't have event listeners directly attached to the elements themselves (i.e. event delegation is being used). See this live example for a demonstration. See also Safari's docs on making elements clickable and the definition of "clickable element".

Known workarounds for this bug:

  • Set cursor: pointer; on the element or any of its ancestors.
  • Add a dummy onclick="void(0)" attribute to the element or any of its ancestors up to but not including <body> (en-US).
  • Use a typically interactive element (e.g., <a>) instead of one that isn't typically interactive (e.g., <div>).
  • Stop using click event delegation.

Safari Mobile considers the following elements to be typically interactive (and thus they aren't affected by this bug):

範例

此範例顯示對<button>的連續點擊次數。

HTML

<button>Click</button>

JavaScript

const button = document.querySelector('button');

button.addEventListener('click', event => {
  button.textContent = `Click count: ${event.detail}`;
});

結果

嘗試快速、重複地點擊按鈕以增加點擊次數。如果您在兩次點擊之間暫停一下,計數將重置。

規範

Specification
UI Events
# event-type-click
HTML Standard
# handler-onclick

瀏覽器兼容性

BCD tables only load in the browser

參見