DIV CSS 佈局教程網

TextRange 物件應用實例:處理文字部分內容與游標定位
編輯:關於JavaScript     

TextRange 物件主要用於處理 JavaScript 中文本的部分內容。它用來表現 HTML 元素裡的文字,雖然平常較少用到,卻早在 IE4.0 時便已提供。不過 TextRange 提供的呼叫方法相對晦澀,那麼我們究竟能用它做些什麼呢?

TextRange 的傳統用途是對使用者在網頁上以滑鼠圈選的文字進行操作,例如變化、刪除、新增等;而它最經典的用途,則是在網頁中搜尋文字與取得輸入框游標的位置。後者又能衍生出更多實用的應用,例如限制輸入的 MaskTextBox(核心技術點就是取得游標位置,再用正則表達式判斷輸入內容),以及「使用方向鍵在輸入框矩陣中自然導航」等。

取得輸入框游標位置的程式碼其實很短,只是這些物件與方法較不常用而已:

<script language="javascript">
function GetCursorPsn(txb) {
  var slct = document.selection;
  var rng = slct.createRange();
  txb.select();
  rng.setEndPoint("StartToStart", slct.createRange());
  var psn = rng.text.length;
  rng.collapse(false);
  rng.select();
  return psn;
}
</script>

不過使用這個 GetCursorPsn() 方法後,會對輸入框操作帶來副作用。對於 <input type="text" onkeydown="GetCursorPsn(this)">,它將無法再以 Shift + 左右方向鍵選取文字;對於 <textarea onkeydown="GetCursorPsn(this)"></textarea>,則無法再以 Shift + 上下左右方向鍵選取文字。原因是程式碼在取得游標到文字起點後,呼叫 rng.collapse(false) 會改變文字框內文字的 EditPoint。

以下先滿足一個實用需求:使用上下左右鍵實現文字方塊的跳轉,同時選取文字方塊內容以便使用者修改:

var range = $currentTextfield.createTextRange(); //$currentTextfield 為 jQuery 物件
range.moveStart('character', 0);
range.select();

最後附上一個關於 TextRange 的完整範例,示範如何取得 textarea 中被選取的文字。範例中提供了兩種實作:方法一利用 document.selection 與 window.getSelection 判斷,方法二則針對 textarea 使用 selectionStart/selectionEnd 屬性擷取選取範圍:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>new document</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
body { font-size: 12px; }
#show { background-color: #CCFF99; }
</style>
</head>
<body>
<textarea id="content" cols="30" rows="10">
河中魚類離奇死亡,下游居民頻染怪病,沿岸植物不斷變異,敬請關注今晚《科學探索》即將播出的專題節目。
</textarea>
<button id="btn">獲取選中值</button>
<div id="show"></div>
<script>
String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, "");
}
/* 方法一 */
function getSelectText() {
  try {
    var selectText = (document.selection && document.selection.createRange) ? document.selection.createRange().text : window.getSelection().toString();
    if (selectText != null && selectText.trim() != "") {
      return selectText;
    }
  } catch (err) {}
}
/* 方法二 */
function getSelectText2(id) {
  var t = document.getElementById(id);
  if (window.getSelection) {
    if (t.selectionStart != undefined && t.selectionEnd != undefined) {
      return t.value.substring(t.selectionStart, t.selectionEnd);
    } else {
      return "";
    }
  } else {
    return document.selection.createRange().text;
  }
}
document.getElementById('btn').onclick = function() {
  document.getElementById('show').innerHTML = getSelectText2('content');
}
</script>
</body>
</html>

透過這些範例可以看出,TextRange 及相關的選取 API 能靈活處理文字內容與游標位置,在表單驗證、輸入限制、鍵盤導航等場景中都有廣泛的應用價值。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved