代码之家  ›  专栏  ›  技术社区  ›  Hank Gay

如何在输入框中突出显示文本的子集?

  •  1
  • Hank Gay  · 技术社区  · 17 年前

    我试图找出是否可以使用JavaScript在文本字段中突出显示特定范围的数据。

    textfield.select();
    

    这^^用于选择整个文本,但在我的谷歌搜索中,我没有偶然发现一种方法来选择输入文本中的字符2到10。这有可能吗?

    3 回复  |  直到 14 年前
        1
  •  2
  •   Diodeus - James MacFarlane    17 年前

    与其他人相比,IE的处理方式有所不同。

    以下是参考指南和示例:

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

        2
  •  1
  •   bobwienholt    17 年前

    我认为有一个非常具体的方法来做它涉及到textrange对象。

    Here's some documentation on the TextRange object.

    在发帖后,我意识到这可能只在文本区工作。

        3
  •  1
  •   Hank Gay    17 年前

    此对象将允许您获取、设置和修改文本框的选定区域。

    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;
      }
    }