滑鼠點選時立即觸發一個事件,而不是在鬆開滑鼠後——JavaScript?


為此,請使用帶有 mousedown 事件的 addEventListener()。

示例

以下是程式碼 -

<!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>

要執行上述程式,請儲存檔名“anyName.html(index.html)”。右鍵單擊該檔案,然後在 VS Code 編輯器中選擇“使用 Live Server 開啟”選項。

輸出

這將在控制檯中產生以下輸出 -

當您單擊滑鼠時,該事件將生成。控制檯輸出如下所示 -

更新於: 09-11-2020

234 次瀏覽

開啟你的 職業生涯

透過完成課程實現認證

開始
廣告