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():返回包含範圍的父元素。var rng = element.createTextRange(); (input, textarea, body 等支援)rng.moveStart("character", 5); rng.moveEnd("character", -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。