jQuery使左键调用右键单击上下文菜单

jQuery使左键调用右键单击上下文菜单,jquery,jquery-plugins,onclick,contextmenu,Jquery,Jquery Plugins,Onclick,Contextmenu,我正在使用我在这里找到的一些功能: 这让我开始制作一个漂亮的上下文菜单。我的目的是让这个上下文菜单在右键或左键点击时“弹出”。但是我可能并不总是想绑定左键单击,所以我需要能够始终执行右键单击,并且在需要时,使用一些代码使左键单击也能工作 首先,为了测试您的演示需要jQuery,我使用的是1.8.2 以下是插件的来源: /* * ContextMenu - jQuery plugin for right-click context menus * * Author: Chris Domiga

我正在使用我在这里找到的一些功能:

这让我开始制作一个漂亮的上下文菜单。我的目的是让这个上下文菜单在右键或左键点击时“弹出”。但是我可能并不总是想绑定左键单击,所以我需要能够始终执行右键单击,并且在需要时,使用一些代码使左键单击也能工作

首先,为了测试您的演示需要jQuery,我使用的是1.8.2

以下是插件的来源:

/*
 * ContextMenu - jQuery plugin for right-click context menus
 *
 * Author: Chris Domigan
 * Contributors: Dan G. Switzer, II
 * Parts of this plugin are inspired by Joern Zaefferer's Tooltip plugin
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Version: r2
 * Date: 16 July 2007
 *
 * For documentation visit http://www.trendskitchens.co.nz/jquery/contextmenu/
 *
 */

(function($) {

    var menu, shadow, trigger, content, hash, currentTarget;
  var defaults = {
    menuStyle: {
      listStyle: 'none',
      padding: '1px',
      margin: '0px',
      backgroundColor: '#fff',
      border: '1px solid #999',
      width: '100px'
    },
    itemStyle: {
      margin: '0px',
      color: '#000',
      display: 'block',
      cursor: 'default',
      padding: '3px',
      border: '1px solid #fff',
      backgroundColor: 'transparent'
    },
    itemHoverStyle: {
      border: '1px solid #0a246a',
      backgroundColor: '#b6bdd2'
    },
    eventPosX: 'pageX',
    eventPosY: 'pageY',
    shadow : true,
    onContextMenu: null,
    onShowMenu: null
    };

  $.fn.contextMenu = function(id, options) {
    if (!menu) {                                      // Create singleton menu
      menu = $('<div id="jqContextMenu"></div>')
               .hide()
               .css({position:'absolute', zIndex:'500'})
               .appendTo('body')
               .bind('click', function(e) {
                 e.stopPropagation();
               });
    }
    if (!shadow) {
      shadow = $('<div></div>')
                 .css({backgroundColor:'#000',position:'absolute',opacity:0.2,zIndex:499})
                 .appendTo('body')
                 .hide();
    }
    hash = hash || [];
    hash.push({
      id : id,
      menuStyle: $.extend({}, defaults.menuStyle, options.menuStyle || {}),
      itemStyle: $.extend({}, defaults.itemStyle, options.itemStyle || {}),
      itemHoverStyle: $.extend({}, defaults.itemHoverStyle, options.itemHoverStyle || {}),
      bindings: options.bindings || {},
      shadow: options.shadow || options.shadow === false ? options.shadow : defaults.shadow,
      onContextMenu: options.onContextMenu || defaults.onContextMenu,
      onShowMenu: options.onShowMenu || defaults.onShowMenu,
      eventPosX: options.eventPosX || defaults.eventPosX,
      eventPosY: options.eventPosY || defaults.eventPosY
    });

    var index = hash.length - 1;
    $(this).bind('contextmenu', function(e) {
      // Check if onContextMenu() defined
      var bShowContext = (!!hash[index].onContextMenu) ? hash[index].onContextMenu(e) : true;
      if (bShowContext) display(index, this, e, options);
      return false;
    });
    return this;
  };

  function display(index, trigger, e, options) {
    var cur = hash[index];
    content = $('#'+cur.id).find('ul:first').clone(true);
    content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(
      function() {
        $(this).css(cur.itemHoverStyle);
      },
      function(){
        $(this).css(cur.itemStyle);
      }
    ).find('img').css({verticalAlign:'middle',paddingRight:'2px'});

    // Send the content to the menu
    menu.html(content);

    // if there's an onShowMenu, run it now -- must run after content has been added
        // if you try to alter the content variable before the menu.html(), IE6 has issues
        // updating the content
    if (!!cur.onShowMenu) menu = cur.onShowMenu(e, menu);

    $.each(cur.bindings, function(id, func) {
      $('#'+id, menu).bind('click', function(e) {
        hide();
        func(trigger, currentTarget);
      });
    });

    menu.css({'left':e[cur.eventPosX],'top':e[cur.eventPosY]}).show();
    if (cur.shadow) shadow.css({width:menu.width(),height:menu.height(),left:e.pageX+2,top:e.pageY+2}).show();
    $(document).one('click', hide);
  }

  function hide() {
    menu.hide();
    shadow.hide();
  }

  // Apply defaults
  $.contextMenu = {
    defaults : function(userDefaults) {
      $.each(userDefaults, function(i, val) {
        if (typeof val == 'object' && defaults[i]) {
          $.extend(defaults[i], val);
        }
        else defaults[i] = val;
      });
    }
  };

})(jQuery);

$(function() {
  $('div.contextMenu').hide();
});
/*
*ContextMenu-用于右键单击上下文菜单的jQuery插件
*
*作者:克里斯·多米根
*贡献者:Dan G.Switzer,II
*这个插件的部分灵感来自Joern Zaeffer的工具提示插件
*
*MIT和GPL许可下的双重许可:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
*版本:r2
*日期:2007年7月16日
*
*有关文件,请访问http://www.trendskitchens.co.nz/jquery/contextmenu/
*
*/
(函数($){
变量菜单、阴影、触发器、内容、哈希、currentTarget;
var默认值={
菜单样式:{
listStyle:'无',
填充:“1px”,
边距:“0px”,
背景颜色:“#fff”,
边框:“1px实心#999”,
宽度:“100px”
},
项目样式:{
边距:“0px”,
颜色:“#000”,
显示:“块”,
游标:“默认值”,
填充:“3px”,
边框:“1px实心#fff”,
背景颜色:“透明”
},
项目悬停样式:{
边框:“1px实心#0a246a”,
背景颜色:“#b6bdd2”
},
eventPosX:'pageX',
eventPosY:“pageY”,
影子:没错,
onContextMenu:null,
onShowMenu:空
};
$.fn.contextMenu=函数(id,选项){
如果(!menu){//创建单例菜单
菜单=$(“”)
.hide()
.css({position:'absolute',zIndex:'500'})
.appendTo('正文')
.bind('click',函数(e){
e、 停止传播();
});
}
如果(!阴影){
阴影=$('')
.css({背景颜色:'#000',位置:'absolute',不透明度:0.2,zIndex:499})
.appendTo('正文')
.hide();
}
散列=散列| |[];
hash.push({
id:id,
menuStyle:$.extend({},defaults.menuStyle,options.menuStyle |{}),
itemStyle:$.extend({},defaults.itemStyle,options.itemStyle |{}),
itemHoverStyle:$.extend({},defaults.itemHoverStyle,options.itemHoverStyle |{}),
绑定:options.bindings | |{},
shadow:options.shadow | | options.shadow==false?options.shadow:defaults.shadow,
onContextMenu:options.onContextMenu | | Default.onContextMenu,
onShowMenu:options.onShowMenu | | Default.onShowMenu,
eventPosX:options.eventPosX | | defaults.eventPosX,
eventPosY:options.eventPosY | | defaults.eventPosY
});
var index=hash.length-1;
$(this).bind('contextmenu',函数(e){
//检查是否定义了onContextMenu()
var bShowContext=(!!哈希[index].onContextMenu)?哈希[index].onContextMenu(e):true;
if(bShowContext)显示(索引、this、e、选项);
返回false;
});
归还这个;
};
功能显示(索引、触发器、e、选项){
var cur=散列[索引];
content=$('#'+cur.id).find('ul:first').clone(true);
content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(
函数(){
$(this.css(cur.itemHoverStyle);
},
函数(){
$(this.css(cur.itemStyle);
}
).find('img').css({verticalAlign:'middle',paddingRight:'2px'});
//将内容发送到菜单
html(content);
//如果有onShowMenu,请立即运行它——必须在添加内容后运行
//如果尝试在menu.html()之前更改内容变量,IE6就会出现问题
//更新内容
如果(!!当前显示菜单)菜单=当前显示菜单(e,菜单);
$.each(cur.bindings,function(id,func){
$('#'+id,menu).bind('click',函数(e){
隐藏();
func(触发器,当前目标);
});
});
css({'left':e[cur.eventPosX],'top':e[cur.eventPosY]}.show();
if(cur.shadow)shadow.css({width:menu.width(),height:menu.height(),left:e.pageX+2,top:e.pageY+2}).show();
$(文档).1('单击',隐藏);
}
函数hide(){
menu.hide();
shadow.hide();
}
//应用默认值
$.contextMenu={
默认值:函数(userDefaults){
$.each(用户默认值、函数(i、val){
if(typeof val=='object'&&defaults[i]){
$.extend(默认值[i],val);
}
否则默认值[i]=val;
});
}
};
})(jQuery);
$(函数(){
$('div.contextMenu').hide();
});
以及我的页面的来源:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/Workflow.dwt.php" codeOutsideHTMLIsLocked="false" -->
    <head>
        <script type="text/javascript" src="../jQuery/jquery-1.8.2.min.js"></script>
        <script type="text/javascript" src="../../Common/clientscript.js"></script>
        <script type="text/javascript" src="jquery.actions.js"></script>
        <script>
            $(document).ready(function() {
                /// Replace the intrinsic Context Menu with MINE
                $('span.infoholder').contextMenu('myMenu',{
                    onContextMenu: function(e)
                    {
                        iDataID = $(e.target).attr('id').replace("menu_","");
                        iGroupID = $(e.target).attr('name');


                    }
                });

                /// Get the Left Click to behave as the right click...
                $("span.infoholder").click(function(event) {
                    alert("I am in " + event.which);
                    // on right click
                    if (event.which == "1")
                    {
                        // prevent left click from being interpreted by the browser:
                        $("#"+$(event.target).attr("id")).trigger({
                            type: 'click',
                            which: 3
                        });
                    }
                });
            });
        </script>
    </head>
    <body>
    <div class="contextMenu" id="myMenu">
        <li>Test 1</li>
        <li>Test 2</li>
    </div>
    <span class="infoholder" id="menu_34675"     name="1"     style="border:solid 1px grey; padding: 2px 5px 2px 5px; background-color:#d9f7ff;">Actions </span><br/><br/>
    <span class="infoholder" id="menu_34735"     name="1"     style="border:solid 1px grey; padding: 2px 5px 2px 5px; background-color:#d9f7ff;">Actions </span><br/><br/>
    </body>
</html>

$(文档).ready(函数(){
///用我的上下文菜单替换固有的上下文菜单
$('span.infoholder').contextMenu('myMenu'{
onContextMenu:函数(e)
{
iDataID=$(e.target).attr('id').replace(“菜单”,”);
iGroupID=$(e.target).attr('name');
}
});
///让左键单击的行为与右键单击的行为相同。。。
$(“span.infoholder”)。单击(函数(事件){
警惕(“我在”+事件中,哪一个);
//右击
如果(event.which==“1”)
{
//防止浏览器对左键单击进行解释:
$(“#”+$(event.target).attr(“id”).trigger({
键入:“单击”,
其中:3
});
}
});
});
  • 测试1
  • 测试2
  • 行动

    $(this).bind('click', function(e) {
        // Check if onContextMenu() defined
        var bShowContext = (!!hash[index].onContextMenu) ? hash[index].onContextMenu(e) : true;
        if (bShowContext) display(index, this, e, options);
        return false;
    });
    
    $(this).bind('click contextmenu', function(e) {
       // Check if onContextMenu() defined
       var bShowContext = (!!hash[index].onContextMenu) ? hash[index].onContextMenu(e) : true;
       if (bShowContext) display(index, this, e, options);
       return false;
    });
    return this;