JavaScript 实现自定义右键菜单

207 阅读1分钟

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

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

以下是代码示例:

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