使用jquery的上下文菜单

时间:2014-04-12 06:21:49

标签: javascript jquery html css

我在Right Click的jquery中有一个上下文菜单。

但它在某种程度上无法满足我的需求。

当我在点击时添加新的div然后尝试对其进行上下文菜单操作时,它就无法正常工作。

正在对原始div进行操作。

有人可以帮助我解决这个问题并改进我的Jquery或HTMl。

Js fiddle for Context Menu

由于

2 个答案:

答案 0 :(得分:2)

正如marck所说,您的代码中存在许多错误。您在多个元素上多次使用相同的ID。无论如何,我创建了一个基本的jsfiddle,你想要实现的目标。您可以在此基础上构建并根据您的需要进行修改。

这是链接: http://jsfiddle.net/PCLwU/

function add(){
 //For adding new items.
}

function menu(){
//to show up context menu
}

function menuactions(){
//Define the actions performed when menu option is selected.
}

针对不同列表的不同上下文菜单:http://jsfiddle.net/PCLwU/3/

答案 1 :(得分:1)

上下文菜单div

<div id='contextMenu'>                         
    <ul id='items'>                        
            <li id="cutDoc">Cut</li>
            <li id="copyDoc">Copy</li>
            <li id="pasteDoc">Paste</li>
            <li id="deleteDocs">Delete</li>
   </ul>
</div>

菜单样式

<style>
    #items
    {
      list-style: none;
      margin: 5px  0 0 5px;
    }
    #contextMenu
    {
      display: none;
      position: fixed;       
      border: 1px solid grey;
      width: 150px;
      background-color:white;
      box-shadow: 2px 2px 1px grey;
    }
    #items li
    {
      list-style-type: none;      
      border-bottom: 1px solid grey;
      border-bottom-style: dotted;
      padding: 10px;
      font-size: 14px; 
    } 
    #items :hover
    {
      background: #0070FF;     
      color: white;
    }
</style>

jQuery用于应用所需区域的脚本

$("YOur class name").mousedown(function(e){
        //to block browsers default right click
        if( e.button == 2 ) {

            $("#contextMenu").css("left", e.pageX);
            $("#contextMenu").css("top", e.pageY);
            $("#contextMenu").fadeIn(500, startFocusOut());
        }
      });

     function startFocusOut() {
            $(document).on("click", function () {   
                $("#contextMenu").hide(500);
                $(document).off("click");           
            });
        }

这样可以正常工作。

更新

here is the fiddle demo