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

狂风中的少年 提交于 2020-03-22 12:32:53

在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 insert18         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 scrollTop23             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"));



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!