Thuộc tính KeyboardEvent.altKey trả về true nếu phím ALT đang được nhấn giữ khi sự kiện bàn phím xảy ra, ngược lại false.
Cú pháp
event.altKey
Ví dụ
<!DOCTYPE html>
<html>
<style>
body { color: #000; height: 100vh; background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat; text-align: center; }
input { border: 2px solid #fff; padding: 8px; background: transparent; width: 310px; border-radius: 20px; outline: none; }
::placeholder { color: #000; }
.show { font-size: 1.2rem; color: #fff; }
</style>
<body>
<h1>Demo KeyboardEvent.altKey</h1>
<input type="text" placeholder="Nhấn phím bất kỳ (thử giữ ALT)" onkeydown="checkAlt(event)">
<div class="show"></div>
<script>
function checkAlt(event) {
var msg = "Phím: " + event.key + " | altKey: " + event.altKey;
if (event.altKey) {
msg += " <span style='color:yellow'>(ALT đang nhấn)</span>";
}
document.querySelector(".show").innerHTML = msg;
}
</script>
</body>
</html>
Kết quả
Nhấn phím bất kỳ → hiển thị tên phím và trạng thái ALT. Giữ ALT + phím khác → altKey: true.
Tương tự: ctrlKey, shiftKey, metaKey (Cmd/Win). Dùng cho shortcut: Ctrl+S, Alt+Enter, Shift+Click...