iT邦幫忙

2024 iThome 鐵人賽

DAY 1
0
JavaScript

PM說: RD大大,這個功能要怎麼寫啊?系列 第 1

PM說: 網頁要怎麼客製化右鍵選單(menu)?

  • 分享至 

  • xImage
  •  

實現重點

加上contextmenu事件監聽,並且阻止預設瀏覽器行為event.preventDefault()

  • 當監聽到右鍵觸發將選單顯示出來
  • click時再把選單隱藏

請參考:
https://developer.mozilla.org/en-US/docs/Web/API/Element/contextmenu_event

Claude Demo

https://claude.site/artifacts/7f9d5ffe-a2b9-4442-8d25-d988ab5c0bd6

上面的範例是: 對 <h1> <img> 標籤右鍵就出現 客製化選單
P.S 在手機上沒有滑鼠右鍵,是長按觸發

程式碼

附上改寫後的程式碼

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>DAY-1 PM說: 網頁要怎麼客製化右鍵選單(menu)?</title>
    <style>
      #custom-menu {
        display: none;
        position: absolute;
        background-color: #f9f9f9;
        border: 1px solid #ccc;
        padding: 5px;
      }
      #custom-menu div {
        padding: 5px;
        cursor: pointer;
      }
      #custom-menu div:hover {
        background-color: #e9e9e9;
      }
      img {
        margin: 2px;
      }
    </style>
  </head>
  <body>
    <h1>右鍵召喚我的分身</h1>
    <img
      src="https://fakeimg.pl/600x270/?text=%E5%8F%B3%E9%8D%B5%E5%8F%AC%E5%96%9A%E6%88%91%E7%9A%84%E5%88%86%E8%BA%AB&font=noto"
      alt="Example image"
    />
    <div id="custom-menu">
      <div id="copy-option">召喚</div>
    </div>
    <script>
      document.addEventListener("DOMContentLoaded", () => {
        const customMenu = document.getElementById("custom-menu");
        const copyOption = document.getElementById("copy-option");
        let targetElement = null;
        // 顯示自定義選單
        document.addEventListener("contextmenu", (e) => {
          if (e.target.tagName === "H1" || e.target.tagName === "IMG") {
            e.preventDefault();
            targetElement = e.target;
            customMenu.style.display = "block";
            customMenu.style.left = e.pageX + "px";
            customMenu.style.top = e.pageY + "px";
          }
        });
        // 隱藏自定義選單
        document.addEventListener(
          "click",
          () => (customMenu.style.display = "none")
        );
        // 複製元素
        copyOption.addEventListener("click", () => {
          if (targetElement) {
            const deep = true;
            // 這邊透過 cloneNode 複製,參數deep控制是否巢狀複製
            // 要注意如果有用到 id, name 屬性要修改避免重複
            const newElement = targetElement.cloneNode(deep);
            targetElement.parentNode.insertBefore(
              newElement,
              targetElement.nextSibling
            );
          }
        });
      });
    </script>
  </body>
</html>

生活中的例子

google地圖 對地點圖標右鍵會發現出現選單

語法學習

https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode


下一篇
PM說: 要怎麼寫一個免費的網頁地圖?
系列文
PM說: RD大大,這個功能要怎麼寫啊?20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言