js实现在光标的位置 添加内容
Posted 枫叶布
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js实现在光标的位置 添加内容相关的知识,希望对你有一定的参考价值。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> </head> <body> <script type="text/javascript"> 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"); } } } </script> <form id="form1" action="" onsubmit="" method="post" enctype="text/plain"> <p> <textarea name="tarea" rows="" cols="" style="width:300px;height:120px;" onselect="setCaret(this);" onclick="setCaret(this);" onkeyup="setCaret(this);" >例子例子例子例子例子</textarea> <br/><br/> <input type="text" name="textfield" style="width:220px;" value="插入FireFox"/> <br/> <input type="button" value="插入" onclick="insertAtCaret(this.form.tarea,this.form.textfield.value);"/> </p> </form> <div id="box" contenteditable="true" style="border:1px solid #ccc; width:300px; height:200px;">sljfldjfldf</div> </body> </html>
以上是关于js实现在光标的位置 添加内容的主要内容,如果未能解决你的问题,请参考以下文章