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


javascript MouseEvent which用法及代碼示例


mouseEvent的哪個屬性用於在觸發鼠標事件時返回與按下的鼠標按鈕對應的數字

用法:

event.which

返回值:它返回一個數字,指示按下了哪個鼠標按鈕:


  • 對於鼠標左鍵:返回1
  • 對於鼠標中鍵:返回2
  • 對於鼠標右鍵:返回3

例:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>mouseEvent which Property</title> 
</head> 
  
<body style="text-align:center;"> 
  
    <h1 style="color:green;"> 
            GeeksforGeeks 
        </h1> 
  
    <h2> 
            mouseEvent which Property 
        </h2> 
  
    <button onmousedown="geek(event)">Click me!</button> 
  
    <p id="p"></p> 
    <script> 
        function geek(event) { 
            if (event.which == 1) { 
                document.getElementById('p').innerHTML = "Left mouse"  
                                              + " button is clicked "; 
            } else if (event.which == 2) { 
                document.getElementById('p').innerHTML = "Middle mouse"  
                                               + " button is clicked "; 
            } else if (event.which == 3) { 
                document.getElementById('p').innerHTML = "Right mouse"  
                                                + "button is clicked "; 
            } 
        } 
    </script> 
</body> 
  
</html>                                

輸出:
單擊按鈕之前:
initial
單擊鼠標左鍵後:
left
單擊鼠標中鍵後:
middle
單擊鼠標右鍵後:
right

支持的瀏覽器:下麵列出了鼠標事件支持的瀏覽器:

  • 蘋果Safari 1.0
  • 穀歌瀏覽器1.0
  • Firefox 1.0
  • Opera 5.0
  • Internet Explorer 9.0


相關用法


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