使用 Javascript 在文本区域的光标处插入文本

2023-12-30

我在网上寻找解决方案,有一些,但它们似乎都将代码拆分为支持 IE 和 Firefox。

我想知道是否有一种更优雅的方法适用于每个浏览器,在光标处插入一些文本textarea.

非常感谢。


不,没有。 IE 有它的TextRange反对做这项工作。 IE >= 9 以及过去很长一段时间以来的所有其他内容selectionStart and 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();
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Javascript 在文本区域的光标处插入文本 的相关文章

随机推荐