---
title: "在 textarea 中光标位置插入字符串"
author: "winzenghua"
date: "2010-12-24T14:56:00Z"
tags: []
slug: "textarea"
draft: false
lastmod: "2010-12-24T14:56:00Z"
id: 947897
url: "https://java4gis.iteye.com/blog/947897"
---

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

![JavaScript: textarea cursor](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[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](http://b3log-solo.googlecode.com/) 从 [Vanessa](http://vanessa.b3log.org:80) 进行同步发布的

原文地址：[http://vanessa.b3log.org/textarea-cursor-insert-string](http://vanessa.b3log.org/textarea-cursor-insert-string)