设置所选文本在 IE 中可见

set the selected text visible in IE

本文关键字:IE 文本 设置      更新时间:2023-09-26
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.但我做不到 5.此问题仅存在于IE9+中

任何解决方案??

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