萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript TextRange 對象詳解:文本範圍選擇、搜索與光標控制

什麼是 TextRange?

TextRange 是 IE 專有的 DHTML 特性,代表文檔中一段文本的範圍,可進行選擇、搜索、修改、光標定位等操作。現代瀏覽器請使用標準 Selection / Range API。

常用屬性

屬性說明
boundingHeight / boundingWidth範圍外接矩形高度/寬度
boundingLeft / boundingTop矩形左/上邊緣相對父坐標位置
htmlText範圍內的 HTML 內容
text範圍內的純文本(可讀寫)

常用方法

  • moveStart(unit, count) / moveEnd(unit, count):移動起始/結束點。unit: character, word, sentence, textedit。
  • move(unit, count):摺疊後移動插入點。
  • collapse(start):摺疊為插入點,start=true 為起點,false 為終點。
  • select():高亮選中範圍文本(光標實現)。
  • findText(string, scope, flags):搜索文本,找到則調整範圍並返回 true。
  • execCommand(cmd):在範圍上執行編輯命令(如粗體、複製)。
  • parentElement():返回包含範圍的父元素。

三步驟基本用法

  1. 創建範圍:var rng = element.createTextRange(); (input, textarea, body 等支援)
  2. 設置起止點:rng.moveStart("character", 5); rng.moveEnd("character", -3);
  3. 操作範圍:rng.select(); 或 rng.text = "新內容";

實例:移動光標到指定位置

<input id="txtTest" value="明·羅貫中《三國演義》..." size="100">
<input id="txtNum" size="5"> <button onclick="moveCursor()">移動</button>
<script>
function moveCursor() {
  var pos = parseInt(document.getElementById("txtNum").value);
  if (isNaN(pos)) return alert("請輸入數字");
  var rng = document.getElementById("txtTest").createTextRange();
  rng.move("character", pos);
  rng.select();
}
</script>

實例:文本框查找下一個

<textarea id="txtBox" rows="7" cols="50">菊花台...</textarea>
<input id="txtFind" value="輸入查詢內容"> <button onclick="findText(txtFind.value)">查找下一個</button>
<script>
var rng = document.getElementById("txtBox").createTextRange();
function findText(str) {
  if (!str) return;
  var num = 0;
  if (document.selection) num = document.selection.createRange().text.length;
  rng.moveStart("character", num);
  rng.moveEnd("character", document.getElementById("txtBox").value.length);
  if (rng.findText(str)) rng.select();
  else { alert("搜索完畢"); rng = document.getElementById("txtBox").createTextRange(); }
}
</script>

注意

TextRange 僅 IE 支援,現代項目請改用 window.getSelection() / document.createRange() 標準 API。

copyright © 萬盛學電腦網 all rights reserved