【问题标题】:How to insert text at the current caret position in a textarea如何在文本区域的当前插入符号位置插入文本
【发布时间】:2011-05-26 06:53:07
【问题描述】:

在从图像调用函数时,我试图将图像中的 alt 标记值插入到插入符号当前位置的文本区域中。

这是我目前拥有的将 alt 标记值插入到文本区域末尾的代码。

    $("#emoticons").children().children().click(function () {
        var ch = $(this).attr("alt");
        $("#txtPost").append(ch);

    }); 

我遇到的两件事是确定插入符号的位置,并使用插入符号位置之前的 textarea 值 + 我要插入的代码 + 之后 textarea 的值创建一个新字符串插入符号位置。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

我目前已经安装了这个扩展:

$.fn.insertAtCaret = function(text) {
    return this.each(function() {
        if (document.selection && this.tagName == 'TEXTAREA') {
            //IE textarea support
            this.focus();
            sel = document.selection.createRange();
            sel.text = text;
            this.focus();
        } else if (this.selectionStart || this.selectionStart == '0') {
            //MOZILLA/NETSCAPE support
            startPos = this.selectionStart;
            endPos = this.selectionEnd;
            scrollTop = this.scrollTop;
            this.value = this.value.substring(0, startPos) + text + this.value.substring(endPos, this.value.length);
            this.focus();
            this.selectionStart = startPos + text.length;
            this.selectionEnd = startPos + text.length;
            this.scrollTop = scrollTop;
        } else {
            // IE input[type=text] and other browsers
            this.value += text;
            this.focus();
            this.value = this.value;    // forces cursor to end
        }
    });
};

你可以像这样使用它:

$("#txtPost").insertAtCaret(ch);

【讨论】:

  • 另外,我很久以前在某人的博客上发现了这个,并将其修改为更加跨浏览器。这不是 100%,但应该可以解决问题。我不记得我在哪里找到它了。
  • @andufo 你为什么不试试呢?
猜你喜欢
  • 1970-01-01
  • 2012-06-20
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 2011-01-08
相关资源
最近更新 更多