日期:2014-05-16  浏览次数:20404 次

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