js自定义右键菜单

本文介绍如何使用JavaScript创建自定义的右键菜单,并通过具体代码示例展示了菜单项的添加、样式设置及事件监听等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

效果显示

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值