使用 JavaScript 選擇和取消選擇元素內部的文字


以下程式碼使用 JavaScript 選擇和取消選擇元素內部的文字 −

示例

 即時演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Select and Deselect Text Inside an Element</h1>
<div style="color: green;" class="result">
Here is some text inside the div
</div>
<button class="Btn">SELECT</button>
<button class="Btn">DESELECT</button>
<h3>Click on the above button to select/de-select text inside the div</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelectorAll(".Btn");
   BtnEle[0].addEventListener("click", () => {
      window.getSelection().selectAllChildren(resEle);
   });
   BtnEle[1].addEventListener("click", () => {
      window.getSelection().removeAllRanges();
   });
</script>
</body>
</html>

輸出

上述程式碼將產生以下輸出 −

單擊“選擇”按鈕 −

單擊“取消選擇”按鈕 −

更新於: 18-7-2020

2K+ 次瀏覽

開啟你的 職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.