Fork me on GitHub

jQuery右键菜单插件contextMenu详细使用说明

简介

jQuery-contextMenu是一个基于jQuery实现的鼠标右键菜单插件,可以轻松的实现鼠标右键点击后展示菜单。
项目地址:https://github.com/swisnl/jQuery-contextMenu

使用说明

基础插件引入

插件依赖jQuery,所以一定要先引入。

1
2
3
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<link href="https://cdn.bootcss.com/jquery-contextmenu/2.6.3/jquery.contextMenu.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery-contextmenu/2.6.3/jquery.contextMenu.min.js"></script>

页面元素

定义一个测试菜单

1
<button type="button" id="test" class="btn btn-primary">鼠标右键测试</button>

js绑定事件

绑定元素右键点击事件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$(document).ready(function() {
$.contextMenu({
selector: '#test', //右键选择器
callback: function(key, options) {//点击回调处理
var m = "clicked: " + key;
window.console && console.log(m) || alert(m);
},
items: {//菜单列表配置
"edit": {name: "Edit", icon: "edit"},
"cut": {name: "Cut", icon: "cut"},
copy: {name: "Copy", icon: "copy"},
"paste": {name: "Paste", icon: "paste"},
"delete": {name: "Delete", icon: "delete"},
"sep1": "---------",
"quit": {name: "Quit", icon: function(){
return 'context-menu-icon context-menu-icon-quit';
}}
}
});
});

自定义按钮图标

图标可以使用FontAwesome图标库,只需要引入样式文件font-awesome.min.css,然后在官网上选择图标。FontAwesome官网

1
<link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

js代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
$(document).ready(function() {
$.contextMenu({
selector: '#test', //右键选择器
callback: function(key, options) {//点击回调处理
var m = "clicked: " + key;
window.console && console.log(m) || alert(m);
},
items: {//菜单列表配置
"download": {name: "下载", icon: "fa-download"},
"fa-lock": {name: "lock", icon: "fa-lock"}
}
});
});

禁用右键菜单

禁用右键菜单按钮,需要配置disabled:true

1
2
3
4
5
6
7
8
9
10
11
12
13
$(document).ready(function() {
$.contextMenu({
selector: '.btn', //右键选择器
callback: function(key, options) {//点击回调处理
var m = "clicked: " + key;
window.console && console.log(m) || alert(m);
},
items: {//菜单列表配置
"download": {name: "下载", icon: "fa-download",disabled: false},
"fa-lock": {name: "lock", icon: "fa-lock",disabled: true}
}
});
});

动态禁用右键菜单

动态禁用可以通过function函数处理。

假如buttion中cutDisabled=”1” 代表禁用,那么具体实例代码如下:

html代码

1
2
<button type="button" class="btn btn-primary">鼠标右键测试1</button>
<button type="button" cutDisabled="1" class="btn btn-primary">鼠标右键测试2</button>

js代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$(document).ready(function() {
$.contextMenu({
selector: '.btn', //右键选择器
callback: function(key, options) {//点击回调处理
var m = "clicked: " + key;
window.console && console.log(m) || alert(m);
},
items: {//菜单列表配置
"download": {name: "下载", icon: "fa-download",disabled: false},
"fa-lock": {name: "lock", icon: "fa-lock",disabled:function(key, opt) {
//假如buttion中cutDisabled="1" 代表禁用
return $(this).attr("cutDisabled") =="1";
}
}
});
});
FallSea wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!