dwz.contextmenu.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * @author zhanghuihua@msn.com
  3. */
  4. (function($){
  5. var menu, shadow, hash;
  6. $.fn.extend({
  7. contextMenu: function(id, options){
  8. var op = $.extend({
  9. shadow : true,
  10. bindings:{},
  11. ctrSub:null
  12. }, options
  13. );
  14. if (!menu) {
  15. menu = $('<div id="contextmenu"></div>').appendTo('body').hide();
  16. }
  17. if (!shadow) {
  18. shadow = $('<div id="contextmenuShadow"></div>').appendTo('body').hide();
  19. }
  20. hash = hash || [];
  21. hash.push({
  22. id : id,
  23. shadow: op.shadow,
  24. bindings: op.bindings || {},
  25. ctrSub: op.ctrSub
  26. });
  27. var index = hash.length - 1;
  28. $(this).bind('contextmenu', function(e) {
  29. display(index, this, e, op);
  30. return false;
  31. });
  32. return this;
  33. }
  34. });
  35. function display(index, trigger, e, options) {
  36. var cur = hash[index];
  37. var content = $(DWZ.frag[cur.id]);
  38. content.find('li').hoverClass();
  39. // Send the content to the menu
  40. menu.html(content);
  41. $.each(cur.bindings, function(id, func) {
  42. $("[rel='"+id+"']", menu).bind('click', function(e) {
  43. hide();
  44. func($(trigger), $("#"+cur.id));
  45. });
  46. });
  47. var posX = e.pageX;
  48. var posY = e.pageY;
  49. if ($(window).width() < posX + menu.width()) posX -= menu.width();
  50. if ($(window).height() < posY + menu.height()) posY -= menu.height();
  51. menu.css({'left':posX,'top':posY}).show();
  52. if (cur.shadow) shadow.css({width:menu.width(),height:menu.height(),left:posX+3,top:posY+3}).show();
  53. $(document).one('click', hide);
  54. if ($.isFunction(cur.ctrSub)) {cur.ctrSub($(trigger), $("#"+cur.id));}
  55. }
  56. function hide() {
  57. menu.hide();
  58. shadow.hide();
  59. }
  60. })(jQuery);