在文本区域的光标处插入文本,使用Javascript [英] Inserting text at cursor in a textarea, with Javascript

查看:92
本文介绍了在文本区域的光标处插入文本,使用Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看了一下网络的解决方案,还有一些,但他们似乎把代码分成支持IE和Firefox。我想知道是否有一个更优雅的方式,可以在每个浏览器上工作,在文本区域的光标插入一些文本。

I've had a look round the web for solutions, and there are some, but they all seem to split code into supporting IE and Firefox. I was wondering if there's a more elegant way which would work on every browser, to insert some text at the cursor in a textarea.

非常感谢,

Rich

推荐答案

不,没有。 IE有它的 TextRange 对象来完成这项工作。 IE> = 9,最后一段时间的所有内容在textareas和文本输入上具有 selectionStart selectionEnd 属性。这个特定的任务不是太糟糕:以下将删除当前选择(如果存在),在插入符处插入文本,并在所有主要浏览器中插入文本后立即重新定位插入符:

No, there isn't. IE has its TextRange objects to do the job. IE >= 9 and everything else for the last long time has selectionStart and selectionEnd properties on textareas and text inputs. This particular task isn't too bad: the following will delete the current selection (if one exists), insert text at the caret and reposition the caret immediately after the inserted text, in all the major browsers:

function insertTextAtCursor(el, text) {
    var val = el.value, endIndex, range;
    if (typeof el.selectionStart != "undefined" && typeof el.selectionEnd != "undefined") {
        endIndex = el.selectionEnd;
        el.value = val.slice(0, el.selectionStart) + text + val.slice(endIndex);
        el.selectionStart = el.selectionEnd = endIndex + text.length;
    } else if (typeof document.selection != "undefined" && typeof document.selection.createRange != "undefined") {
        el.focus();
        range = document.selection.createRange();
        range.collapse(false);
        range.text = text;
        range.select();
    }
}

这篇关于在文本区域的光标处插入文本,使用Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆