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

好久没晒代码了。今天心情不错,搬出来晒晒太阳。
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 = document.body.createTextRange(); // Don't: oR = textarea.createTextRange() 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') { i ++; } } return i; } } var insertString = function () { // TODO: should be insert it at the after of cursor 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) { 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 进行同步发布的
Tags:  js字符串位置

延伸阅读

最新评论

发表评论