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


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。