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();
}
相关推荐
程序员大阳5 分钟前
副队长CSS教程(33)–圆角与透明
前端·css·透明·圆角
志尊宝16 分钟前
Vue3 零基础每日笔记(082):文件上传实战——el-upload 校验、自定义上传、头像预览
前端·javascript·vue.js·笔记·#javascript·#vue.js
鬼手点金41 分钟前
opencode-rules 插件
java·开发语言·前端·人工智能·chrome·git·github
柳杉42 分钟前
借助 Codex 和可视化工作流,从调研到完整实现,3D 大屏竟然可以这么简单
前端·ai编程·数据可视化
IMPYLH1 小时前
HTML 的 <wbr> 元素
前端·html
Dovis(誓平步青云)2 小时前
常用命令藏得太深?怎么做一个快捷命令坞
运维·前端·自动化·音视频·prometheus
IT_陈寒2 小时前
Vite的这个问题坑了我三天,原来如此解决!
前端·人工智能·后端
网易云信2 小时前
大模型能上岗做销售吗?我们让 12 款国产模型交了 420 份作业
前端·后端
蜗牛互联网3 小时前
Python Agent工具调用的白名单、参数校验与审批门禁
java·服务器·前端·人工智能·后端·python
计算机魔术师3 小时前
Perplexity:每个 Project 都是一个 Git 仓库
前端