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


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