在IE中设置所选文本

时间:2014-12-29 08:55:22

标签: javascript jquery html5 internet-explorer-11

1 Programmatically inserting text into a text box
2 Setting the caret to the end.
3 Making the caret visible (i.e. scroll the text box content)
4 Select some of the text from last programmatically,
5 **set the selected text visible.** (i.e. scroll the text box content)

我可以做1,2,3,4。但我无法做到。这个问题只存在于IE9 +

任何解决方案??

1 个答案:

答案 0 :(得分:1)

setSelectionRange()不完全支持IE。

所以经过谷歌搜索后我用下面的代码替换它,它对我有用。

function setSelection(field, start, charsTobeSelected) {
    end = start + charsTobeSelected;
    if (field.createTextRange) {
        var selRange = field.createTextRange();
        selRange.collapse(true);
        selRange.moveStart('character', start);
        selRange.moveEnd('character', end);
        selRange.select();
        field.focus();
    } else if (field.setSelectionRange) {
        field.focus();
        field.setSelectionRange(start, end);
    } else if (typeof field.selectionStart != 'undefined') {
        field.selectionStart = start;
        field.selectionEnd = end;
        field.focus();
    }
}