在光标选择处插入指定文字

在IE和FF下,对于文本域或文本框有效。

在IE下,对容器和文本域或文本框均有效。

 1 var obj = document.getElementById('content'); 
2 (function Insert(obj,str)
3 {
4 //IE下支持document.selection
5 if (document.selection)
6 {
7 obj.focus();
8 sel = document.selection.createRange();
9 sel.text = str;
10 sel.select();
11 }
12 //MOZILLA/NETSCAPE 支持对象的selectionStart和selectionEnd;
13 else if (obj.selectionStart || obj.selectionStart == '0')
14 {
15 var startPos = obj.selectionStart;
16 var endPos = obj.selectionEnd;
17 // save scrollTop before insert
18 var restoreTop = obj.scrollTop;
19 obj.value = obj.value.substring(0, startPos) + str + obj.value.substring(endPos,obj.value.length);
20 if (restoreTop > 0)
21 {
22 // restore previous scrollTop
23 obj.scrollTop = restoreTop;
24 }
25 obj.focus();
26 obj.selectionStart = startPos + str.length;
27 obj.selectionEnd = startPos + str.length;
28 } else {
29 obj.value += str;
30 obj.focus();
31 }
32 }(obj,"texttexttexttext"));



原文地址:https://www.cnblogs.com/zzbo/p/2343243.html