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


HTML oncontextmenu事件用法及代码示例


右键单击一个元素以打开上下文菜单时,将发生HTML DOM oncontextmenu事件。

注意:所有浏览器均支持oncontextmenu事件,但Firefox仅支持contextmenu属性。

用法:


HTML:

<element oncontextmenu="myScript">

JavaScript:

object.oncontextmenu = function(){myScript};

在JavaScript中,使用addEventListener()方法:

object.addEventListener("contextmenu", myScript);

范例1:使用HTML

<!DOCTYPE html> 
<html> 
  
<head> 
    <style> 
        div { 
            background:green; 
            border:1px solid black; 
            padding:10px; 
        } 
    </style> 
</head> 
  
<body> 
    <center> 
        <h1 style="color:green"> 
          GeeksforGeeks 
      </h1> 
        <h2>HTML DOM oncontextmenu Event</h2> 
        <div oncontextmenu="myFunction()" 
             contextmenu="mymenu"> 
            <p>Right-click inside the box 
        </div> 
  
        <script> 
            function myFunction() { 
                alert("right-clicked"); 
            } 
        </script> 
    </center> 
</body> 
  
</html>

输出:
之前:

后:

范例2:使用JavaScript

<!DOCTYPE html> 
<html> 
  
<head> 
    <style> 
        div { 
            background:green; 
            border:1px solid black; 
            padding:10px; 
        } 
    </style> 
</head> 
  
<body> 
    <center> 
        <h1 style="color:green"> 
          GeeksforGeeks 
      </h1> 
        <h2>HTML DOM oncontextmenu Event</h2> 
        <div id="myDIV" contextmenu="mymenu"> 
            <p>Right-click inside the box 
        </div> 
  
        <p id="try"></p> 
  
        <script> 
            document.getElementById( 
              "myDIV").oncontextmenu = function() { 
                GFGfun() 
            }; 
  
            function GFGfun() { 
                var gfg = document.getElementById("try"); 
                gfg.innerHTML = "right-clicked"; 
            } 
        </script> 
    </center> 
</body> 
  
</html>

输出:
之前:

后:

例:在JavaScript中,使用addEventListener()方法:

<!DOCTYPE html> 
<html> 
  
<head> 
    <style> 
        div { 
            background:green; 
            border:1px solid black; 
            padding:10px; 
        } 
    </style> 
</head> 
  
<body> 
    <center> 
        <h1 style="color:green"> 
          GeeksforGeeks 
      </h1> 
        <h2>HTML DOM oncontextmenu Event</h2> 
        <div id="myDIV" contextmenu="mymenu"> 
            <p>Right-click inside the box 
        </div> 
  
        <p id="try"></p> 
  
        <script> 
            document.getElementById( 
                "myDIV").addEventListener("contextmenu", GFGfun); 
  
            function GFGfun() { 
                var gfg = document.getElementById("try"); 
                gfg.innerHTML = "right-clicked"; 
            } 
        </script> 
    </center> 
</body> 
  
</html>

输出:
之前:

后:

支持的浏览器:DOM oncontextmenu Event支持的浏览器如下:

  • 谷歌浏览器
  • IE浏览器
  • Firefox
  • 苹果Safari
  • Opera


相关用法


注:本文由纯净天空筛选整理自Vijay Sirra大神的英文原创作品 HTML | DOM oncontextmenu Event。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。