您的位置:首页 > Web前端 > JavaScript

js自定义右键菜单

2018-01-29 20:04 225 查看

js自定义右键菜单

要把一些小东西记录下来,

function Mmenu(nodeId, list) {
this.window = window;
if (!nodeId || !list) {
throw '参数不全'
}
this.list = list;
this.nodeId = nodeId;
this.node = document.getElementById(nodeId);
if (!this.node) {
throw `${nodeId}该节点不存在`
}
Mmenu.blackTheme(this.node.style)
for (let item in list) {
Mmenu.childNode(item, list, this.node);
}
// 创建样式表
let _style = document.createElement("style");
document.head.appendChild(_style);
let sheet = _style.sheet;
sheet.addRule('.menu-li:hover', 'background-color: #99cc66');
sheet.addRule('.menu-li', 'padding: 10px 10px 10px 20px;');
};
Mmenu.prototype.init = function() {
Mmenu.blackTheme(this.node.style)
this.window.oncontextmenu = (e) => {
e.preventDefault();
let style = this.node.style;
style.display = 'block';
style.left = e.clientX + 'px';
style.top = e.clientY + 'px';
}
this.window.onclick = (e) => {
this.node.style.display = 'none'
}
};
Mmenu.blackTheme = (style) => {
style.backgroundColor = '#333333';
style.color = '#ffffff';
style.width = '110px';
style.height = '132px';
style.paddingTop = '5px';
style.cursor = 'pointer';
style.borderRadius = '6px';

};
Mmenu.childNode = (item, list, node) => {
let li = document.createElement('li');
li.style.listStyle = 'none';
li.innerHTML = item;
li.onclick = list[item];
li.setAttribute('class', 'menu-li')
node.appendChild(li)
}


方法调用

let menu = new Mmenu('menu', {
'删除': _delete,
'打开': _open,
'下载': _download
});
menu.init()

function _delete() {
alert('delete')
};

function _open() {
alert('open');
};

function _download() {
alert('download');
};


效果显示

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: