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

本文介绍了一种在多行文本框中兼容Internet Explorer和Firefox浏览器的光标位置插入字符的方法。通过使用JavaScript实现了不同浏览器环境下的文本插入功能,并提供了一个具体的实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 因项目需要,需要在多行文本框中的光标位置插入字符,利于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中调试通过!!   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值