使用Javascript在textarea中的光标处插入文本

ric*_*w81 6 javascript textarea cross-browser cursor

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

非常感谢,

丰富

Tim*_*own 21

不,没有.IE有其TextRange目标来完成这项工作.IE> = 9,一切过去很长一段时间了selectionStart,并selectionEnd在文字区域和文本输入性能.此特定任务也不错:以下内容将删除当前选择(如果存在),在插入符号处插入文本并在插入的文本后立即重新定位插入符号,在所有主流浏览器中:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)


jig*_*fox 0

实现两者:支持 FF 的代码和支持 IE 的代码。您可以使用框架为两种浏览器编写代码。框架将完成消除浏览器之间差异的工作。

很遗憾,浏览器并非 100% 兼容!