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

来源:互联网 发布:罅隙歌词 知乎 编辑:程序博客网 时间:2024/05/21 11:31

好久没晒代码了。今天心情不错,搬出来晒晒太阳。

JavaScript: textarea cursor

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
原创粉丝点击