jQuery - 右键菜单插件contextMenu使用详解5(快捷键、动态创建菜单)
十二、菜单项快捷键
我们可以通过 accesskey 这个属性给菜单项设置对应的快捷键。配置后只要按下这个键就相当于点击相应的菜单项。
1,效果图
- 菜单打开后,我们按下键盘上的“e”键,相当于点击了“编辑”项。按下“c”键,相当于点击了“剪切”项。
- 快捷键按下后与直接点击菜单项一样,会触发相应的回调函数,同时也会关闭菜单。

2,样例代码
<button class="context-menu-one">按钮1</button> <script type="text/javascript"> $(function() { //初始化菜单 $.contextMenu({ selector: '.context-menu-one', callback: function(key, options) { console.log("点击了:" + key); }, items: { "edit": { name: "编辑 (E)", icon: "edit", accesskey: "e" }, "cut": { name: "剪切 (C)", icon: "cut", accesskey: "c" }, } }); }); </script>
十三、按需动态创建菜单
1,实现原理
- 有时我们的菜单项在初始化的时候并不能确定,或者说需要动态变化(即使是同一个触发元素),那么借助 build 这个配置项即可实现。
- build 方法在每次弹出菜单前都会调用,我们可以在这里返回菜单项,以及相应的点击回调方法。
2,效果图
这里我们在菜单项上添加个一个随机数,会发现菜单每次打开后该数字都是不同的,说明菜单时动态创建的。

3,样例代码
<button class="context-menu-one">按钮1</button> <script type="text/javascript"> $(function() { //初始化菜单 $.contextMenu({ selector: '.context-menu-one', build: function($trigger, e) { // this callback is executed every time the menu is to be shown // its results are destroyed every time the menu is hidden // e is the original contextmenu event, // containing e.pageX and e.pageY (amongst other data) return { callback: function(key, options) { console.log("点击了:" + key); }, items: { "edit": {name: "编辑", icon: "edit"}, "cut": {name: "随机数:" + Math.random(), icon: "cut"} } }; } }); }); </script>
4,功能改进
下面是动态菜单配合通过代码打开菜单的样例。不管是左键还是右键按钮点击,都会出现菜单。<button class="context-menu-one">按钮1</button> <script type="text/javascript"> $(function() { //初始化菜单 $.contextMenu({ selector: '.context-menu-one', trigger: 'none', build: function($trigger, e) { e.preventDefault(); //从 trigger 中获取动态创建的菜单项及回掉 return $trigger.data('runCallbackThingie')(); } }); //动态创建菜单项及回调 function createSomeMenu() { return { callback: function(key, options) { var m = "clicked: " + key; window.console && console.log(m) || alert(m); }, items: { "edit": {name: "编辑", icon: "edit"}, "cut": {name: "随机数:" + Math.random(), icon: "cut"} } }; } //按年点击是弹出菜单 $('.context-menu-one').on('mouseup', function(e){ var $this = $(this); //将动态创建的菜单项及回掉保存在 trigger 中 $this.data('runCallbackThingie', createSomeMenu); var _offset = $this.offset(), position = { x: _offset.left + 10, y: _offset.top + 10 } //打开菜单 $this.contextMenu(position); }); }); </script>