如何使用javascript在光标位置的textarea中添加文

如何使用javascript在光标位置的textarea中添加文

本文介绍了如何使用javascript在光标位置的textarea中添加文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里构建一个简单的模板系统.基本上,我设置了将预设变量添加到 textarea 中的按钮.

I'm building a simple templating system here. Basically I've set up buttons that add preset variables into a textarea.

问题是我希望能够在光标所在位置的 textarea 中添加文本.就像您在编辑器窗口中单击URL链接以在stackoverflow上查看此处的帖子一样,该链接也会添加到光标所在的位置.

The thing is that I want to be able to add text in my textarea at the position where my cursor is. Just like when you click on the URL link in the editor window for posts here at stackoverflow the link is added at the position where your cursor is.

我该怎么做?可以使用原型JS完成吗?

How can I do that? And can it be done using prototype JS?

推荐答案

在IE中有点棘手,它在这种情况下做得非常糟糕.下面的代码将在文本区域或文本输入中当前选择的末尾插入文本(如果未选择文本,则在插入符号处插入文本),然后将光标置于文本之后:

It's a bit tricky in IE, which does an exceptionally bad job of this kind of thing. The following will insert text at the end of the current selection in a textarea or text input (or at the caret if the no text is selected) and then position the cursor after the text:

演示: http://jsfiddle.net/RqTvT/1/

代码:

function getInputSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

function offsetToRangeCharacterMove(el, offset) {
    return offset - (el.value.slice(0, offset).split("\r\n").length - 1);
}

function setSelection(el, start, end) {
    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        el.selectionStart = start;
        el.selectionEnd = end;
    } else if (typeof el.createTextRange != "undefined") {
        var range = el.createTextRange();
        var startCharMove = offsetToRangeCharacterMove(el, start);
        range.collapse(true);
        if (start == end) {
            range.move("character", startCharMove);
        } else {
            range.moveEnd("character", offsetToRangeCharacterMove(el, end));
            range.moveStart("character", startCharMove);
        }
        range.select();
    }
}

function insertTextAtCaret(el, text) {
    var pos = getInputSelection(el).end;
    var newPos = pos + text.length;
    var val = el.value;
    el.value = val.slice(0, pos) + text + val.slice(pos);
    setSelection(el, newPos, newPos);
}

var textarea = document.getElementById("your_textarea");
insertTextAtCaret(textarea, "[INSERTED]");

这篇关于如何使用javascript在光标位置的textarea中添加文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 20:44