winzenghua 发表于 2013-2-7 08:16:50

在 textarea 中光标位置插入字符串

好久没晒代码了。今天心情不错,搬出来晒晒太阳。
http://vanessa.b3log.org/datastore-file-access.do?oId=1293180850782

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);            var key = this.className,            textValue= $comment.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.createTextRange();                oR.collapse(true);                oR.moveStart('character', endPosition + 6);                oR.select();            } else {                $comment.setSelectionRange(endPosition + 6, endPosition + 6);            }      });    }

<div style="">本文是使用 B3log Solo 从 Vanessa 进行同步发布的
页: [1]
查看完整版本: 在 textarea 中光标位置插入字符串