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

Trigger event ทันทีที่คลิกเมาส์ (mousedown) ไม่รอปล่อย - JavaScript

ใช้ addEventListener() กับ event mousedown แทน click

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<body></body>
<script>
  document.addEventListener("mousedown", function () {
    console.log("Mouse down event is happening");
  });
</script>
</html>

บันทึกเป็น index.html เปิดด้วย Live Server

ผลลัพธ์

กดเมาส์ (ยังไม่ปล่อย) → event ยิงทันที แสดงในคอนโซล

Trigger event ทันทีที่คลิกเมาส์ (mousedown) ไม่รอปล่อย - JavaScript

Trigger event ทันทีที่คลิกเมาส์ (mousedown) ไม่รอปล่อย - JavaScript

คำอธิบาย: mousedown ยิงเมื่อกดปุ่มเมาส์ลง mouseup ยิงเมื่อปล่อย click ยิงหลัง mousedown+mouseup บน element เดียวกัน ใช้ mousedown สำหรับการตอบสนองเร็ว (เช่น game, drag)