簡體   English   中英

如何在輸入框中突出顯示文本的子集?

[英]How can I highlight a subset of the text in an input box?

我試圖弄清楚是否可以使用Javascript來突出顯示文本字段中的特定數據范圍。

textfield.select();

^^用於選擇整個文本,但對於我的所有谷歌搜索,我沒有偶然發現選擇的方法,例如,輸入文本的字符2到10。 這可能嗎?

IE與其他人的處理方式不同。

以下是參考指南,其中包含示例:

http://www.sxlist.com/techref/language/html/ib/Scripting_Reference/trange.htm

我認為有一種非常特定於IE的方法,它涉及TextRange對象。

這是TextRange對象的一些文檔。

發布后我意識到這可能只適用於textarea。

此對象將允許您獲取,設置和修改文本框的選定區域。

function SelectedText(input) {
  // Replace the currently selected text with the given value.
  this.replace = function(text) {
    var selection = this.get();

    var pre = input.value.substring(0, selection.start);
    var post = input.value.substring(selection.end, input.value.length);

    input.value = pre + text + post;

    this.set(selection.start, selection.start + text.length);

    return this;
  }

  // Set the current selection to the given start and end points.
  this.set = function(start, end) {
    if (input.setSelectionRange) {
      // Mozilla
      input.focus();
      input.setSelectionRange(start, end);
    } else if (input.createTextRange) {
      // IE
      var range = input.createTextRange();
      range.collapse(true);
      range.moveEnd('character', end);
      range.moveStart('character', start);
      range.select();
    }

    return this;
  }

  // Get the currently selected region.
  this.get = function() {
    var result = new Object();

    result.start = 0;
    result.end = 0;
    result.text = '';

    if (input.selectionStart != undefined) {
      // Mozilla
      result.start = input.selectionStart;
      result.end = input.selectionEnd;
    } else {
      // IE
      var bookmark = document.selection.createRange().getBookmark()
      var selection = inputBox.createTextRange()
      selection.moveToBookmark(bookmark)

      var before = inputBox.createTextRange()
      before.collapse(true)
      before.setEndPoint("EndToStart", selection)

      result.start = before.text.length;
      result.end = before.text.length + selection.text.length;
    }

    result.text = input.value.substring(result.start, result.end);

    return result;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM