2009-02-17 100 views
1

我想弄清楚是否有可能使用Javascript突出顯示文本字段中的特定數據範圍。如何突出顯示輸入框中的文本子集?

textfield.select(); 

這^^工程,選擇整個文本,但我所有的谷歌搜索我沒有在一個方式來選擇迷迷糊糊的,例如,人物2通過輸入文本的10。這可能嗎?

回答

1

這個對象將讓你得到,設置&修改文本框的選定區域。

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; 
    } 
} 
相關問題