好久沒曬代碼了。今天心情不錯,搬出來晒晒太陽。
var getCursorEndPosition = function (textarea) { textarea.focus(); // 首先當然要設為選中了 if (textarea.setSelectionRange) { // W3C return textarea.selectionEnd; } else if (document.selection) { // IE var i = 0, oS = document.selection.createRange(), // 當前選中地區,記錄了當前游標起始和結束位置的資訊,可和 oR 進行對比得出當前游標位置。 oR = document.body.createTextRange(); // 不可使用 oR = textarea.createTextRange(), 否則不可與 oS 進行 compareEndPoints。 oR.moveToElementText(textarea); oS.getBookmark(); for (i = 0; oR.compareEndPoints("StartToStart", oS) < 0 && oS.moveStart("character", -1) !== 0; i ++) { if (textarea.value.charAt(i) == '/n') { // 換行 +1。 i ++; } } return i; } }var insertString = function () { var $comment = $("#comment"); var endPosition = getCursorEndPosition($comment[0]); var key = this.className, textValue = $comment[0].value; textValue = textValue.substring(0, endPosition) + key + textValue.substring(endPosition, textValue.length); $("#comment" + name).val(textValue); if ($.browser.msie) { // 出現換行時,位置應 -1。 endPosition -= textValue.split('/n').length - 1; var oR = $comment[0].createTextRange(); oR.collapse(true); oR.moveStart('character', endPosition + 6); oR.select(); } else { $comment[0].setSelectionRange(endPosition + 6, endPosition + 6); } }); }
本文是使用 B3log Solo 從 Vanessa 進行同步發布的原文地址:http://vanessa.b3log.org/textarea-cursor-insert-string