如果在 IE 中最后附加光标,则在光标位置的文本区域中插入文本

inserting text in textarea at cursor position if cursor placed else text should append at last in IE

本文关键字:光标 位置 文本 区域 插入文本 最后 如果 IE      更新时间:2023-09-26

如果放置光标,我想在光标位置的文本区域中插入文本,否则应在IE中现有文本的末尾附加文本。

我使用了这个函数,它在 Mozilla 中工作正常,但在 ie 中不能正常工作,它附加在现有文本的起始位置。

function insertAtCursor(text) {   
    var field = document.frmMain.Expression;
    if (document.selection) {
        field.focus();
        sel = document.selection.createRange();
        sel.text = text;
    }
}

如果没有放置光标,我想在 ie 中现有文本的末尾附加文本。

检查字段是否已具有焦点,如果是,请使用从所选内容生成的TextRange。如果没有,请为字段创建一个TextRange并将其折叠到末尾。

在其他浏览器中,您似乎没有任何用于在光标处插入文本的代码,但也许您遗漏了该位。

现场演示:http://jsbin.com/ixoyes/2

法典:

function insertAtCursor(text) {   
    var field = document.frmMain.Expression;
    if (document.selection) {
        var range = document.selection.createRange();
        if (!range || range.parentElement() != field) {
            field.focus();
            range = field.createTextRange();
            range.collapse(false);
        }
        range.text = text;
        range.collapse(false);
        range.select();
    }
}