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');
};