Skip to content
html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    html, body {
      height: 100%;
    }

    .contextmenu {
      position: fixed;
      z-index: 999;
    }

    .contextmenu ul {
      box-sizing: border-box;
      width: 200px;
      border: 1px solid #DADCE0;
    }

    .contextmenu ul li {
      padding: 0 30px;
      height: 30px;
      line-height: 30px;
      cursor: pointer;
      color: #202124;
      list-style: none;
    }

    .contextmenu ul li:hover {
      background: skyblue;
    }
  </style>
</head>
<body>
  <script id="script">
    window.addEventListener('contextmenu', e => {
      // 阻止弹出浏览器自带的菜单
      e.preventDefault()
      
      let contextmenu = document.querySelector('.contextmenu')
      const body = document.body

      if (!contextmenu) {
        // 创建菜单
        contextmenu = document.createElement('div')
        contextmenu.className = 'contextmenu'
        contextmenu.innerHTML = `
          <ul>
            <li>foo</li>
            <li>bar</li>
            <li>...</li>
          </ul>
        `
        body.appendChild(contextmenu)
      }

      const { clientX, clientY } = e
        
      contextmenu.style.cssText = `
        top: ${ clientY + 10 }px;
        left: ${ clientX + 10 }px;
        opacity: 1;
      `
    })

    window.addEventListener('click', e => {
      const { target } = e

      // 点击菜单内容
      if (target.tagName === 'LI') {
        // ...
      }

      // 菜单消失
      const contextmenu = document.querySelector('.contextmenu')
      if (contextmenu) {
        contextmenu.style.opacity = 0
      }
    })
  </script>
</body>
</html>