如何在文字選擇時顯示自定義選單?


在一些文字編輯器中,當您選擇文字時,它會顯示編輯文字的選單,並提供諸如文字對齊、調整文字大小、更改顏色等功能。Microsoft Word 是最好的例子。在 Microsoft Word 中,當您選擇任何文字時,它都會顯示自定義水平選單以對文字執行某些操作。

本教程將使用 JavaScript 在文字選擇時建立自定義選單。

語法

使用者可以按照以下語法在文字選擇時顯示自定義選單。

let coOrdinates = document.querySelector(".content").getBoundingClientRect();
let posX = clientX - Math.round(coOrdinates.left) + "px";
let posY = clientY - Math.round(coOrdinates.top) - 25 + "px";     

在上述語法中,我們獲取內容 div 的座標。之後,我們找到自定義文字選單的 x 和 y 位置。接下來,我們可以使用 JavaScript 更改自定義文字選單的位置。

步驟

  • 步驟 1 − 在 HTML 中,建立一個 div 並新增文字。此外,建立一個自定義選單並使用 CSS 對其進行樣式設定。

  • 步驟 2 − 在 JavaScript 中,使用 addEventListner() 方法,當發生“mousedown”事件時,獲取點選位置的座標並將其儲存在“clientX”和“clientY”變數中。

  • 步驟 3 − 當文件上觸發“mouseup”事件時,使用 getSelection() 方法獲取選定的 HTML。

  • 步驟 4 − 使用 toString() 方法將 HTML 轉換為文字。

  • 步驟 5 − 檢查文字。如果文字為空,則隱藏自定義選單。

  • 步驟 6 − 如果使用者選擇了某些文字,則獲取所選文字的座標。

  • 步驟 7 − 定義“posX”變數並存儲自定義選單的水平位置。此外,定義“posY”變數以儲存自定義選單的垂直位置。

  • 步驟 8 − 使用“posX”和“posY”變數的值設定自定義選單的左和頂部位置。

示例

在下面的示例中,我們建立了 div 元素並添加了一些文字內容。此外,我們建立了自定義選單並使用 CSS 對其進行了樣式設定。在自定義選單中,我們添加了複製和剪下文字。

在 JavaScript 中,我們實現了上述步驟以在使用者選擇某些文字時顯示自定義選單。在輸出中,使用者可以嘗試選擇文字,他們將在文字頂部看到自定義選單。

<html>
<head>
   <style>
      .hoverMenu { display: none; position: absolute; background: #a4a4a4; border-radius: 6px; height: 30px; }
      .hoverMenu span{ color: #000; cursor: pointer; margin: 8px;}
   </style>
</head>
<body>
   <div class = "content">
      <h2>Showing custom menu on text selection</h2>
      <p>Select some text to see custom menu</p>
      <p>TutorialsPoint is an online platform that provides free tutorials and resources on various programming languages, software tools, and technologies. </p>
      <div class = "hoverMenu"> <span> Copy </span> <span> Cut </span> </div>
   </div>
   <script>
      var clientX, clientY;
      document.addEventListener("mousedown", function (event) { clientX = event.pageX; clientY = event.pageY;});
      document.addEventListener("mouseup", () => {
         let selectionFromDocument = document.getSelection();
         let textValue = selectionFromDocument.toString();
         var hoverMenu = document.querySelector(".hoverMenu");
         if (textValue == "") { hoverMenu.style.display = "none";
         } else {
            // get coOrdinates of the content div
            let coOrdinates = document.querySelector(".content").getBoundingClientRect();
            // set the display style of the hoverMenu to block
            hoverMenu.style.display = "flex";
            // set the position of the hoverMenu
            let posX = clientX - Math.round(coOrdinates.left) + "px";
            hoverMenu.style.left = posX;
            posY = clientY - Math.round(coOrdinates.top) - 25 + "px";
            hoverMenu.style.top = posY;
         }
      });
   </script>
</body>
</html>

使用者學習瞭如何在文字選擇時顯示一些自定義文字選單。在這裡,我們在自定義文字選單中只添加了文字,但是使用者也可以根據需要新增功能。例如,當我們點選複製文字時,它應該將其複製到剪貼簿。

要顯示文字選擇上的自定義選單,請獲取所選文字的座標,並相應地設定選單的位置。

更新於:2023年4月5日

694 次檢視

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.