當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


javascript MouseEvent Button用法及代碼示例


MouseEvent按鈕屬性用於定義左或右鍵事件。單擊鼠標按鈕時,它將返回一個整數值,該整數值描述鼠標左鍵,右鍵或中鍵。

用法:

event.button

返回值:此事件在單擊鼠標事件時返回整數值:


  • 0:它指示鼠標左鍵。
  • 1:它指示鼠標中鍵。
  • 2:它指示鼠標右鍵。

onmousedown事件:當用戶在元素上按下鼠標按鈕時,將發生此事件。

程序1:

<!DOCTYPE html> 
<html> 
    <head> 
        <title>JavaScript Mouse Event</title> 
        <style> 
            body { 
                text-align:center; 
            } 
            .gfg { 
                font-size:40px; 
                font-weight:bold; 
                color:green; 
            } 
        </style> 
    </head> 
    <body> 
        <div class = "gfg">GeeksforGeeks</div> 
        <h2>Mouse click event</h2> 
        <button onclick="click(event)">Click me</button> 
        <p id="demo"></p> 
        <script> 
            document.onmousedown = click 
               
            // click function called 
            function click(event) { 
                  
                // Condition to disable left click 
                if (event.button == 0) { 
                          alert("Left click not allowed"); 
                } 
            } 
        </script> 
    </body> 
</html>

輸出:
right click

程序2:

<!DOCTYPE html> 
<html> 
    <head> 
        <title>JavaScript Mouse Event</title> 
        <style> 
            body { 
                text-align:center; 
            } 
            .gfg { 
                font-size:40px; 
                font-weight:bold; 
                color:green; 
            } 
        </style> 
    </head> 
    <body> 
        <div class = "gfg">GeeksforGeeks</div> 
        <h2>Mouse click event</h2> 
        <button onclick="click(event)">Click me</button> 
        <p id="demo"></p> 
        <script> 
            document.onmousedown = click 
               
            // click function called 
            function click(event) { 
                  
                // Condition to disable left click 
                if (event.button == 2) { 
                          alert("Right click not allowed"); 
                } 
            } 
        </script> 
    </body> 
</html>

輸出:
right click



相關用法


注:本文由純淨天空篩選整理自Naman_Garg大神的英文原創作品 JavaScript | MouseEvent Button Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。