2014-11-03 272 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

工作