UIEvent: which property

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Thuộc tính chỉ đọc UIEvent.which của giao diện UIEvent trả về số cho biết nút nào trên chuột được nhấn, hoặc keyCode số hoặc mã ký tự (charCode) của phím được nhấn trên bàn phím.

Giá trị

Giá trị cho KeyboardEvent Non-standard

Đối với KeyboardEvent, event.which chứa mã số cho một phím cụ thể được nhấn, tùy thuộc vào phím chữ hoặc số hay phím không phải chữ số được nhấn. Vui lòng xem KeyboardEvent.charCodeKeyboardEvent.keyCode đã lỗi thời để biết thêm chi tiết.

Note: Hãy xem xét KeyboardEvent.key hoặc KeyboardEvent.code cho code mới.

Giá trị cho MouseEvent Non-standard

Đối với MouseEvent, event.which là số đại diện cho một nút nhất định:

  • 0: Không có nút
  • 1: Nút trái
  • 2: Nút giữa (nếu có)
  • 3: Nút phải

Đối với chuột được cấu hình cho người thuận tay trái, các hành động nút bị đảo ngược. Trong trường hợp này, các giá trị được đọc từ phải sang trái.

Note: Hãy xem xét MouseEvent.button cho code mới.

Ví dụ

html
<p>Please press any key.</p>
js
function showKeyPress(evt) {
  console.log(
    `onkeypress handler:\n` +
      `keyCode property: ${evt.keyCode}\n` +
      `which property: ${evt.which}\n` +
      `charCode property: ${evt.charCode}\n` +
      `Character Key Pressed: ${String.fromCharCode(evt.charCode)}\n`,
  );
}

function keyDown(evt) {
  console.log(
    `onkeydown handler:\n` +
      `keyCode property: ${evt.keyCode}\n` +
      `which property: ${evt.which}\n`,
  );
}

document.addEventListener("keypress", showKeyPress);
document.addEventListener("keydown", keyDown);

Thông số kỹ thuật

Specification
UI Events
# dom-uievent-which

Tương thích trình duyệt

Xem thêm