Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

แอตทริบิวต์เหตุการณ์ onkeydown ใน HTML

แอตทริบิวต์เหตุการณ์ onkeydown ใน HTML ถูกกระตุ้นเมื่อผู้ใช้กำลังกดปุ่มบนคีย์บอร์ด (ค้างอยู่)

ไวยากรณ์

<tagname onkeydown="script">เนื้อหา</tagname>

ตัวอย่าง

<!DOCTYPE html>
<html>
<head>
<style>
  body { color: #000; height: 100vh; background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat; text-align: center; padding: 20px; }
  .show { font-size: 1.2rem; }
</style>
</head>
<body>
<h1>ตัวอย่างแอตทริบิวต์เหตุการณ์ onkeydown ของ HTML</h1>
<textarea class="" placeholder="ป้อนข้อความที่นี่" rows="5" cols="40" onkeydown="keyFn()"></textarea>
<div class="show"></div>
<script>
  function keyFn() { document.querySelector(".show").innerHTML = 'คุณพิมพ์: ' + document.querySelector("textarea").value; }
</script>
</body>
</html>

ผลลัพธ์

พิมพ์ข้อความใน textarea สีขาวเพื่อดูการทำงานของ onkeydown

จะแสดงข้อความ "คุณพิมพ์: [ข้อความที่พิมพ์]" ขณะกดค้างปุ่ม