`

javascript实现textarea中光标处插入字符的实现[兼容ie和firefox](来自网络)

 
阅读更多

 因项目需要,需要在多行文本框中的光标位置插入字符,利于js的 document.selection属性很快就实现,但发现在firefox中无法兼容selection属性,网上找了很久也没有找到合适的方法,经过研究,改出了兼容ie和FF的完美解决方案
代码如下:

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->function AddText(str) { var ubb=document.getElementById("TxtContent"); var ubbLength=ubb.value.length; ubb.focus(); if(typeof document.selection !="undefined") { document.selection.createRange().text=str; } else { ubb.value=ubb.value.substr(0,ubb.selectionStart)+str+ubb.value.substring(ubb.selectionStart,ubbLength); } }

例如:

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->function Underline() { var tUnderline=prompt("请输入要设置的下划线文字\n标签:[u][/u]","") if(tUnderline==""|| tUnderline==null) { return; } tUnderline="[u]"+tUnderline+"[/u]" AddText(tUnderline); }

HTML部分:

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --><a href="javascript:Underline();void(0)"><img src="Images/Style/underline.gif" alt="下线线" border="0"/></a>

注:1、TxtContent为textarea的ID,函数str参数为要插入的字符
2、在ie6.0和FF2.0中调试通过!!   

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics