contextmenu.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Author:antianlu
  3. * Date:2012-04-21
  4. * Plugin name:jQuery.Contextmenu
  5. * Address:http://www.oschina.net/code/snippet_153403_9880
  6. * Version:0.2
  7. * Email:atlatl333@126.com
  8. */
  9. (function(cm){
  10. jQuery.fn.WinContextMenu=function(options){
  11. var defaults={
  12. offsetX:2,//鼠标在X轴偏移量
  13. offsetY:2,//鼠标在Y轴偏移量
  14. speed:300,//特效速度
  15. flash:!1,//特效是否开启,默认不开启
  16. flashMode:'',//特效模式,与flash为真时使用
  17. cancel:!1,//排除不出现右键菜单区域
  18. items:[],//菜单项
  19. action:$.noop()//自由菜单项回到事件
  20. };
  21. var opt=cm.extend(true,defaults,options);
  22. function create(e){
  23. var m=cm('<ul class="WincontextMenu"></ul>').appendTo(document.body);
  24. cm.each(opt.items,function(i,itm){
  25. if(itm){
  26. var row=cm('<li><a class="'+(itm.disable?'cmDisable':'')+'" ref="sitem" href="javascript:void(0)"><span></span></a></li>').appendTo(m);
  27. itm.icon?cm('<img src="'+itm.icon+'">').insertBefore(row.find('span')):'';
  28. itm.text?row.find('span').text(itm.text):'';
  29. if(itm.action) {
  30. row.find('a').click(function(){this.className!='cmDisable'?itm.action(e):null;});}
  31. }
  32. });
  33. if(cm('#WincontextMenu').html()!=null){
  34. cm(cm('#WincontextMenu').html().replace(/#/g,'javascript:void(0)')).appendTo(m);}
  35. return m;
  36. }
  37. if(opt.cancel){//排除不出现右键菜单区域
  38. cm(opt.cancel).live('contextmenu',function(e){return false});}
  39. this.live('contextmenu',function(e){
  40. var m=create(e).show();
  41. var l = e.pageX + opt.offsetX,
  42. t = e.pageY+opt.offsetY,
  43. p={
  44. wh:cm(window).height(),
  45. ww:cm(window).width(),
  46. mh:m.height(),
  47. mw:m.width()
  48. }
  49. t=(t+p.mh)>=p.wh?(t-=p.mh):t;//当菜单超出窗口边界时处理
  50. l=(l+p.mw)>=p.ww?(l-=p.mw):l;
  51. m.css({zIndex:1000001, left:l, top:t}).live('contextmenu', function() { return false; });
  52. m.find('a').click(function(e){//呼叫新从页面增加的菜单项
  53. var b=$(this).attr('ref');
  54. if(b!='sitem'){this.className!='cmDisable'?opt.action(this):null;}
  55. e.preventDefault();
  56. });
  57. cm(document.body).live('contextmenu click', function() {//防止有动态加载的标签失效问题
  58. m.remove();
  59. });
  60. return false;
  61. });
  62. return this;
  63. }
  64. })(jQuery);