使用jQuery选择输入框内的部分字符串

Luk*_*asz 18 javascript jquery

我试图弄清楚如何使用jQuery突出显示输入框内的文本的某些部分.突出显示输入框的全部内容非常简单,但是如何突出显示一个单词或几个字母呢?

谢谢!

Tim*_*own 35

对于文本<input>元素,以下内容将完成此任务.该示例仅在输入中选择单词"two":

function setInputSelection(input, startPos, endPos) {
    input.focus();
    if (typeof input.selectionStart != "undefined") {
        input.selectionStart = startPos;
        input.selectionEnd = endPos;
    } else if (document.selection && document.selection.createRange) {
        // IE branch
        input.select();
        var range = document.selection.createRange();
        range.collapse(true);
        range.moveEnd("character", endPos);
        range.moveStart("character", startPos);
        range.select();
    }
}

document.getElementById("setSelection").onmousedown = function() {
    var input = document.getElementById("i");
    setInputSelection(input, 4, 7);
    return false;
};
Run Code Online (Sandbox Code Playgroud)
<input id="i" type="text" value="One two three">
<input type="button" value="Set selection" id="setSelection">
Run Code Online (Sandbox Code Playgroud)