2014-11-03 136 views
0

已經仔細閱讀:How to add a custom right-click menu to a webpage?創建上下文菜單

所以我有2個HTML文件和1個JS腳本。我根本不使用JQuery。

popup.html

<!DOCTYPE html> 
    <head> 
     <title id="title">Datajuggler</title> 
    </head> 
    <body> 
     <script src="popup.js"></script> 
    </body> 
</html> 

popup.js

var xhr = new XMLHttpRequest(); 
xhr.open("GET", "contextmenu.html"); 
xhr.send(); 

document.addEventListener("contextmenu", function(e) { 
    // how do I draw the context menu here? 
    e.preventDefault(); 
}); 

contextmenu.html

<div id="menu"> 
    <ul> 
     <li><a href="http://www.google.com">Google</a></li> 
     <li><a href="http://www.youtube.com">Youtube</a></li> 
    </ul> 
</div> 

所以這是非常簡單的。我從contextmenu.html拉上下文菜單HTML,並且我希望這個div顯示每當我用鼠標右鍵單擊(contextmenu事件監聽器)。但是,如何顯示這個div來代替默認的上下文菜單?

謝謝。

回答

0

快速實施和測試此:

popup.html:

<!DOCTYPE html> 
    <head> 
     <title id="title">Datajuggler</title> 
     <style> 
      html{ 
       height: 100%; 
      } 
      body { 
       min-height: 100%; 
       position: relative; 
      } 
      #menu{ 
       position: absolute; 
       border: 1px solid black; 
      } 
     </style> 
    </head> 
    <body> 
     <script src="popup.js"></script> 
    </body> 
</html> 

注:

  • 如果body爲空=>height: 0px(所以您的點擊事件贏得了」待檢測)

  • 包括你的腳本只是</body>結束標記

  • 位置你的菜單absolute

contextmenu.html前:

<div id="menu" style="display: none"> 
    <ul> 
     <li><a href="http://www.google.com">Google</a></li> 
     <li><a href="http://www.youtube.com">Youtube</a></li> 
    </ul> 
</div> 

注:

  • 隱藏男人U(設置display:none

popup.js:

xhr.onreadystatechange = function(){ 
    if (xhr.readyState == 4 && xhr.status == 200){ 

     // append the menu to `body` 
     document.body.innerHTML += xhr.responseText; 

     var menu = document.getElementById('menu'); 

     // overwrite the right click event 
     document.addEventListener("contextmenu", function(e) {  
      e.preventDefault();   
      // show the menu   
      menu.style.display = 'block'; 
      // set the left and top position based on mouse event coordonates 
      menu.style.left = e.x + 'px'; 
      menu.style.top = e.y + 'px';   
     }); 

     // close the menu on document click 
     // TODO verify if the click is in the menu boundaries 
     document.addEventListener("click", function(e){ 
      menu.style.display = 'none'; 
     }); 
    } 
} 

// make xhr `async` request => third param `true` 
xhr.open("GET", "contextmenu.html", true); 
xhr.send(); 

注:

  • 打開網頁瀏覽器控制檯(F12)=>進入JavaScript控制檯,看看是否有是否有任何錯誤

  • 在上測試應用程序(Web服務器),否則你的xhr不會因爲 cross origin

工作