1

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

我已经使用了这个函数,它在 Mozilla 中运行良好,但在它附加到现有文本的起始位置时却没有。

function insertAtCursor(text) {   

    var field = document.frmMain.Expression;

    if (document.selection) {

        field.focus();

        sel = document.selection.createRange();
        sel.text = text;
    }
}

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

4

1 回答 1

3

检查该字段是否已经具有焦点,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();
    }
}
于 2012-07-06T10:15:24.107 回答