html代码
<!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"> <script type="text/javascript" src="111.js"></script> <form id="form1" action="" onsubmit="" method="post" enctype="text/plain"> <p> <textarea name="tarea" rows="" cols="" style="300px;height:120px;" onclick="setCaret(this);" >哈哈按钮 大阿萨德发按时</textarea> <br/><br/> <input type="text" name="textfield" style="220px;" value="插入FireFox"/> <br/> <input type="button" value="插入" onclick="insertAtCaret(this.form.tarea,this.form.textfield.value);"/> </p> </form> </html>
js代码,名为111.js
function setCaret(textObj) { if (textObj.createTextRange) { textObj.caretPos = document.selection.createRange().duplicate(); } } function insertAtCaret(textObj, textFeildValue) { if (document.all) { if (textObj.createTextRange && textObj.caretPos) { var caretPos = textObj.caretPos; caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? textFeildValue + ' ' : textFeildValue; } else { textObj.value = textFeildValue; } } else { if (textObj.setSelectionRange) { var rangeStart = textObj.selectionStart; var rangeEnd = textObj.selectionEnd; var tempStr1 = textObj.value.substring(0, rangeStart); var tempStr2 = textObj.value.substring(rangeEnd); textObj.value = tempStr1 + textFeildValue + tempStr2; } else { alert("This version of Mozilla based browser does not support setSelectionRange"); } } }
插入后效果