前端之家收集整理的这篇文章主要介绍了
使用Javascript在textarea中的光标处插入文本,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经浏览了网络上的
解决方案,还有一些,但它们似乎都将
代码拆分为
支持IE和Firefox.我想知道是否有更优雅的方式可以在每个浏览器上工作,在文本区域的光标处插入一些文本.
非常感谢,
丰富
@H_
502_9@
不,没有. IE有TextRange对象来完成这项工作. IE> = 9,最后一段时间的所有其他
内容在textareas和文本输入上都有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();
}
}