【问题标题】:inserting text in textarea at cursor position if cursor placed else text should append at last in IE如果光标放置,则在光标位置的文本区域中插入文本,否则文本应最后附加在 IE 中
【发布时间】:2012-07-06 09:57:54
【问题描述】:

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

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

function insertAtCursor(text) {   

    var field = document.frmMain.Expression;

    if (document.selection) {

        field.focus();

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

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

【问题讨论】:

    标签: javascript


    【解决方案1】:

    检查该字段是否已经具有焦点,如果是,则使用从选择中生成的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();
        }
    }
    

    【讨论】:

    • 非常感谢您的回复,我现在可以解决我的问题了。
    • 嗨,如果我在单击按钮时附加一个按钮的值,这可以正常工作。我还需要一个要求,当我单击一个按钮时,下拉选择的选项也应该被附加。它被附加在 0 位置而不是最后一个位置。函数 addSyntax(){ var field = document.getElementById("operatorSelect");变量值 = ''; if(field != '') { value = field.options[field.selectedIndex].value; insertAtCursorOld(value) field.selectedIndex = 0; } } 请帮帮我。
    • @user1506292:这似乎是一个单独的问题,虽然我不完全理解你在问什么。你能举个例子吗?
    • 在您提供的示例中,当我在光标位于 textarea 文本中间时单击按钮时,提供的文本附加在光标位置,当我单击第二个时光标立即返回结束时间连续。我希望它本身在那里可用。这个 unselectable="on" 事情只起到了一半的作用。当我单击按钮的边框时,光标会留在后面,否则会消失。请帮我解决这个问题。
    猜你喜欢
    • 2011-07-09
    • 2016-04-30
    • 2012-10-27
    • 2012-06-20
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2011-10-21
    相关资源
    最近更新 更多