Posted in Javascript onMarch 22, 2013
下面是代码:
-------------------------------------------------------------------------------- <!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> <script type="text/javascript"> function insertAtCursor(myField, myValue) { //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; sel.select(); } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; // save scrollTop before insert www.keleyi.com var restoreTop = myField.scrollTop; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); if (restoreTop > 0) { myField.scrollTop = restoreTop; } myField.focus(); myField.selectionStart = startPos + myValue.length; myField.selectionEnd = startPos + myValue.length; } else { myField.value += myValue; myField.focus(); } } </script> </head> <body> <div style="width:500px;margin-left:auto;margin-right:auto;margin-top:100px;"> <textarea id="keleyi_com" style="width:340px; height:180px"> 柯乐义 Javascript 在textarea光标处插入文本 </textarea> <input type="button" onclick="insertAtCursor(document.getElementById('keleyi_com'),'www.keleyi.com')" value="插入文本" /> </div></body> </html>
JS在textarea光标处插入文本的小例子
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@