js在光标位置插入内容
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2016-05-01 11:35:24
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>js在光标处插入内容</title> </head> <body> <script> //objid:textarea的id str:要插入的内容 function insertstr(objid,str){ var myField=document.getElementById(""+objid); //IE浏览器 if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = str; sel.select(); } //火狐/网景 浏览器 else if (myField.selectionStart || myField.selectionStart == '0') { //得到光标前的位置 var startPos = myField.selectionStart; //得到光标后的位置 var endPos = myField.selectionEnd; // 在加入数据之前获得滚动条的高度 var restoreTop = myField.scrollTop; myField.value = myField.value.substring(0, startPos) + str + myField.value.substring(endPos, myField.value.length); //如果滚动条高度大于0 if (restoreTop > 0) { // 返回 myField.scrollTop = restoreTop; } myField.focus(); myField.selectionStart = startPos + str.length; myField.selectionEnd = startPos + str.length; } else { myField.value += str; myField.focus(); } } </script> <textarea style="width:500px; height:300px;" id="a"></textarea> <input type="button" value="456" onclick="insertstr('a',this.value)"/> </body> </html>