JavaScript 实现自定义右键菜单

在JavaScript中,自定义鼠标右键菜单通常涉及以下几个步骤:

  1. 阻止默认的右键菜单显示
  2. 监听鼠标右键点击事件
  3. 创建自定义的右键菜单界面、在右键点击事件触发时显示自定义菜单
  4. 为自定义菜单添加功能逻辑

以下是代码示例:

js 复制代码
const menus = [
    {
        label: '自定义菜单',
        onClick() {
            console.log('自定义菜单');
        },
    },
    {
        label: '自定义返回',
        onClick() {
            console.log('自定义返回');
        },
    },
    {
        label: '自定义刷新',
        onClick() {
            console.log('自定义刷新');
        },
    },
];

const ContextMenu = (() => {
    let instance;

    const ContextMenu = function ({ menus = [] }) {
        if (instance) {
            return instance;
        }

        this.menus = menus;

        return instance = this;
    };

    const wrapStyle = `
        position: fixed;
        padding: 12px;
        border-radius: 2px;
        box-sizing: border-box;
        box-shadow: 4px 4px 4px 4px #ececec;
        z-index: 999;
    `;
    const itemStyle = `
        line-height: 24px;
        font-size: 10px;
        color: #303133;
        cursor: default;
    `;

    ContextMenu.prototype.create = function () {
        if (this.menuWrap) {
            return this.menuWrap;
        }

        this.menuWrap = document.createElement('div');
        this.menuWrap.style.cssText = wrapStyle;

        for (let menu of this.menus) {
            const item = document.createElement('div');
            item.style.cssText = itemStyle;
            item.textContent = menu.label;
            item.onclick = menu.onClick;

            this.menuWrap.appendChild(item);
        }

        document.body.appendChild(this.menuWrap);

        return this.menuWrap;
    }

    ContextMenu.prototype.remove = function () {
        if (this.menuWrap) {
            document.body.removeChild(this.menuWrap);
            this.menuWrap = null;
        }
    };

    return ContextMenu;
})();

const contextMenu = new ContextMenu({ menus });

document.addEventListener('contextmenu', (e) => {
    e.preventDefault();
    createMenu(e);
});

document.addEventListener('click', removeMenu);

function createMenu(e) {
    const menu = contextMenu.create();
    menu.style.top = `${e.clientY}px`;
    menu.style.left = `${e.clientX}px`;
}

function removeMenu(e) {
    contextMenu.remove();
}
相关推荐
qq_363066931 分钟前
react 使用web component导出静态html报告
前端·react.js·html·页面导出
weixin_457763084 分钟前
展示youtube的视频
前端·javascript·html
雨翼轻尘5 分钟前
03_HTML进阶标签与CSS入门
前端·css·html·入门·进阶标签
云水一下5 分钟前
Vue.js从零到精通系列(六):组合式函数与逻辑复用——打造自己的 Hooks 工具箱
前端·javascript·vue.js
IT_陈寒6 分钟前
Java的ArrayList扩容把我坑惨了,原来是这样搞的
前端·人工智能·后端
snow@li7 分钟前
Charles:软件能力深度解析 / 跨平台 HTTP/HTTPS 代理调试工具 / 客户端与互联网之间的中间人代理 / 拦截、查看、篡改所有网络流量
前端
Pearson11 分钟前
特大pdf文件在线预览技术方案
javascript·nginx·pdf
UXbot13 分钟前
移动端UI设计工具选型指南:iOS与Android设计标准支持对比
android·前端·低代码·ios·交互·团队开发·ui设计
GuWen_yue15 分钟前
吃透二叉树与递归!60分钟掌握树结构核心+解题思路
javascript·算法