解决方法
从这里复制
Caret position in textarea,in characters from the start见
DEMO.
<script src="jquery.js"></script> <script> $(function () { $('#txt').keyup(function (e){ if(e.keyCode == 13){ var curr = getCaret(this); var val = $(this).val(); var end = val.length; $(this).val( val.substr(0,curr) + '<br>' + val.substr(curr,end)); } }) }); function getCaret(el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(),rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart',re); return rc.text.length; } return 0; } </script> <div id="content"> <textarea id="txt" cols="50" rows="10"></textarea> </div>
好吧,我想所有文本编辑器(WYSIWYG)都会一直这样做.