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

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

回过头来看看,代码有问题,继续修改下。2012-10-24

<html>
    <body>
        <textarea onmouseup="getCursorInfo(this)" onkeyup="setPosition(this)">123456</textarea>
        <script>
            var getCursorInfo = function (textarea) {
                var result = {};
                if (textarea.setSelectionRange) { 
                    // W3C
                    result.end = textarea.selectionEnd;
                    result.start = textarea.selectionStart;
                    result.text = textarea.value.substring(result.start, result.end);
                } else if (document.selection) { 
                    // IE
                    var i = 0,
                    oS = document.selection.createRange(),
                    // Don't: oR = textarea.createTextRange()
                    oR = document.body.createTextRange();
                    oR.moveToElementText(textarea);
                    result.text = oS.text;
                    oS.getBookmark();
                    // object.moveStart(sUnit [, iCount])
                    // Return Value: Integer that returns the number of units moved.
                    for (i = 0; oR.compareEndPoints('StartToStart', oS) < 0 && oS.moveStart("character", -1) !== 0; i ++) {
                        // Why? You can alert(textarea.value.length)
                        if (textarea.value.charAt(i) == '/n') {
                            i ++;
                        }
                    }

                    result.start = i;
                    result.end = i + result.text.length;
                }

                return result;
            }

            var setPosition = function (textarea) {
                if (textarea.setSelectionRange) { 
                    textarea.setSelectionRange(2, 6);
                } else {
                    var oR = textarea.createTextRange();
                    oR.collapse(true);
                    oR.moveStart('character', 2);
                    oR.moveEnd('character', 6);
                    oR.select();
                }
            }
        </script>
    </body>
</html>