TextRange 是早期 IE 提供的動態 HTML 特性,讓你能以「字元」為單位隨意框選文件中的文字,而不受限於瀏覽器原生的選取行為。它可以拿來做即時搜尋、光標定位、特定字串反白等效果。以下整理其屬性、方法與典型用法。
瀏覽器原生的選取(selection)是以「使用者用滑鼠刷過的範圍」為單位,程式很難精準控制。TextRange 則把「一段文字」抽象成有明確起點與終點的物件,你可以用字元計數的方式移動這兩個端點,再將結果套用成選取。一句話概括:它是文件文字流上的可程式化選取框。
texthtmlTextboundingHeight / boundingWidthoffsetLeft / offsetTopcreateTextRange()move(unit, count)character/word/sentence/textedit)位移 count 個單位。正數往前、負數往後。moveStart(unit, count) / moveEnd(unit, count)collapse(boolean)select()findText(str, scope, flags)parentElement()const rng = input.createTextRange();moveStart / moveEnd 決定要框住哪一段select() 反白、findText() 搜尋、text 讀寫內容
<input type="text" id="txtTest" size="60"
value="明·羅貫中《三國演義》第二十一回:夫英雄者,胸懷大志,腹有良謀。">
<br>
移動光標到第 <input type="text" id="txtNum" size="4"> 個位置
<input type="button" value="移動" onclick="moveCursor()">
<script>
function moveCursor() {
const pos = Number(document.getElementById('txtNum').value);
if (Number.isNaN(pos)) { alert('請輸入一個數字'); return; }
const rng = document.getElementById('txtTest').createTextRange();
rng.move('character', pos); // 先收縮成插入點再位移
rng.select(); // 套用為選取(此時起訖重合,看起來就是光標)
}
</script>
「光標」在 TextRange 的模型裡其實就是起點與終點重合的範圍,這點理解之後很多事情就通了。
function selectInner() {
const box = document.getElementById('txtBox');
const rng = box.createTextRange();
rng.moveStart('character', 1); // 起點往前一格
rng.moveEnd('character', -1); // 終點往後一格
rng.select();
}
預設情況下範圍起點在容器第一個字元、終點在最後一個字元之後,所以各移動一格就能去掉首尾。
const box = document.getElementById('txtBox');
const rng = box.createTextRange();
function findNext(str) {
if (!str) return;
if (rng.findText(str)) {
rng.select(); // 反白找到的內容
rng.collapse(false); // 把起點移到這次的終點,下次才能繼續往後找
} else {
alert('搜尋完畢');
rng = box.createTextRange(); // 重置,否則永遠搜不到
}
}
這段有兩個關鍵:每次找到後要 collapse(false),否則下一次搜尋會從同一個位置開始而永遠停在第一筆;搜到底要重設 range,否則範圍已被壓縮到尾端,再也找不到任何東西。
findText 的另外兩個參數:scope 指定搜尋的距離上限(負值代表往前搜),flags 用位元組合成設定行為——2 表示只匹配整個單字、4 表示區分大小寫,兩者並用則是 2 ^ 4 = 6。
function showContainer() {
const rng = document.selection.createRange();
alert(rng.parentElement().tagName);
}
TextRange 是微軟專屬的舊技術,在非 IE 瀏覽器中完全不存在,而且 IE 本身也已停止維護。新專案請改用標準的 Selection 與 Range API:
const selection = window.getSelection();
const range = document.createRange();
// 選取某元素全部內容
range.selectNodeContents(document.getElementById('target'));
selection.removeAllRanges();
selection.addRange(range);
// 搜尋則用 window.find(str) 或自行遍歷文字節點
標準 Range 用 setStart() / setEnd() 搭配 DOM 節點與偏移量來定位,概念與 TextRange 相似但更精確(能跨越元素邊界)。把這份筆記當成「文字範圍操作」的觀念入門即可,實際實作請走標準 API。