javascript右键菜单

 

 

文章来源:https://segmentfault.com/a/1190000023098787

 

HTML

<h1>Click on blank to show custom context menus</h1>

CSS

复制代码
.custom-context-menu {
  position: fixed;
  border: 1px solid #ccc;
  list-style: none;
  padding: 4px 0;
  border-radius: 4px;
  box-shadow: 0px 2px 6px 2px #ddd;

  &.hidden {
    display: none;
  }

  li {
    padding: 8px 12px;
    border-bottom: 1px solid #f0f2f5;
    user-select: none;
    transition: all 0.1s;

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      cursor: pointer;
      background-color: #0170fe;
      color: #fff;
    }

    &:active {
      background-color: #f0f2f7;
    }
  }
}
复制代码

JS

复制代码
/**
 * options:
 * {
 *  menus:[{
 *    name: string,
 *    onClick: Function
 *  }],
 * }
 */
const ContextMenu = function (options) {
  let instance;

  function createMenu() {
    const ul = document.createElement("ul");
    ul.classList.add("custom-context-menu");
    const { menus } = options;
    if (menus && menus.length > 0) {
      for (let menu of menus) {
        const li = document.createElement("li");
        li.textContent = menu.name;
        li.onclick = menu.onClick;
        ul.appendChild(li);
      }
    }
    const body = document.querySelector("body");
    body.appendChild(ul);
    return ul;
  }

  return {
    getInstance: function () {
      if (!instance) {
        instance = createMenu();
      }
      return instance;
    },
  };
};

const contextMenu = ContextMenu({
  menus: [
    {
      name: "custom menu 1",
      onClick: function (e) {
        console.log("menu1 clicked");
      },
    },
    {
      name: "custom menu 2",
      onClick: function (e) {
        console.log("menu2 clicked");
      },
    },
    {
      name: "custom menu 3",
      onClick: function (e) {
        console.log("menu3 clicked");
      },
    },
  ],
});

function showMenu(e) {
  e.preventDefault();
  const menus = contextMenu.getInstance();
  menus.style.top = `${e.clientY}px`;
  menus.style.left = `${e.clientX}px`;
  menus.classList.remove("hidden");
}

function hideMenu(event) {
  const menus = contextMenu.getInstance();
  menus.classList.add("hidden");
}

document.addEventListener("contextmenu", showMenu);
document.addEventListener("click", hideMenu);
复制代码

 

 

链接:https://codepen.io/mudontire/pen/ZEQvRNX

 

posted @   漫漫长路</>  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示