2014-08-29 84 views
0

问题:上下文菜单正常工作,但如果您在多个div上拉出上下文菜单,它会记住点击事件。使菜单被拉起的部分特定的上下文菜单事件

要重新创建:右键单击一个部分。点击菜单外部关闭它(不要选择一个选项)。点击另一部分并选择一个选项。如果删除,它将删除菜单被拉出的两个部分。如果您选择向下移动该部分,则会移动菜单拉出的第一部分。

问题:如何优化下面的JS/Jquery来保持菜单事件的菜单被拉起的部分?

JS Fiddle

$(".templateSection").contextmenu(function (event) { 
    var thisTemplate = this; 
    // Avoid the real one 
    event.preventDefault(); 

    // Show contextmenu 
    $(".custom-menu").toggle(100).  
    // In the right position (the mouse) 
    css({ 
     top: event.pageY + "px", 
     left: event.pageX + "px" 
    }); 
    $(".editArea").css('outline', 'none') 
    //Delete section menu button 
    $("#menuDelete").click(function() { 
     $(thisTemplate).remove(); 
     $(".custom-menu").hide(100); 
    });  
    //Move sections up and down 
    function firstAndLast(container) { 
     firstAndLast($('#container')); 
    }  
    $('.menuUp, .menuDown').click(function (e) { 
     e.preventDefault(); 

     var parent = $(thisTemplate).closest('.templateSection'), 
      grandparent = $(thisTemplate).closest('#container'); 

     if ($(this).hasClass('menuUp')) { 
      parent.insertBefore(parent.prev('.templateSection')); 
      firstAndLast(grandparent); 

     } else if ($(this).hasClass('menuDown')) { 
      parent.insertAfter(parent.next('.templateSection')); 
      thisTemplate.clearQueue(); 
     } 
    }); 

    // Hide menu if the document is clicked somewhere 
    $(document).bind("mousedown", function (e) { 
     //left mouse down 
     switch (e.which) { 
      case 1: 
       // If the clicked element is not the menu 
       if (!$(e.target).parents(".custom-menu").length > 0) { 
        // Hide it 
        $(".custom-menu").hide(100); 
       } 
     }  
    }); 
}); 

回答

0

更改JS到下面的代码。如果给出更优化的解决方案,我会改变接受的答案。

JS Fiddle

//Replace default context menu on right click 
$(function() { 
    $('.custom-menu').hide(); 
    $(".templateSection").contextmenu(function (e) { 
     e.preventDefault(); 
     thisTemplate = this; 
     $(".custom-menu").css({ 
      top: event.pageY + "px", 
      left: event.pageX + "px" 
     }).fadeIn(200); 
    }); 
}); 

//Delete Section 
$("#menuDelete").click(function() { 
    $(thisTemplate).remove(); 
    $(".custom-menu").hide(100); 
}); 

//Move sections up and down 
$('.menuUp, .menuDown').click(function() { 
    var parent = $(thisTemplate).closest('.templateSection'); 
    if ($(this).hasClass('menuUp')) { 
     parent.insertBefore(parent.prev('.templateSection')); 
    } else if ($(this).hasClass('menuDown')) { 
     parent.insertAfter(parent.next('.templateSection')); 
    } 
}); 

$(document).mousedown(function (e) { 
    //left mouse down 
    switch (e.which) { 
     case 1: 
      // If the clicked element is not the menu 
      if (!$(e.target).parents('.custom-menu').length > 0) { 
       $(".custom-menu").hide(100); 
      } 
    } 
});