当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。