在 textarea 中游標位置插入字串

來源:互聯網
上載者:User

好久沒曬代碼了。今天心情不錯,搬出來晒晒太陽。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.