如何在textarea中的当前插入位置插入文本 [英] How to insert text at the current caret position in a textarea

查看:167
本文介绍了如何在textarea中的当前插入位置插入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在图像的函数调用中,我试图将图像中的alt标记值插入到插入符当前位置的textarea中。

On a function call from an image, I am trying to insert the alt tag value from the image into the textarea at the position where the caret currently is.

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

This is the code that I currently have which inserts the alt tag value to the end of the text area.

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

    }); 

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

The 2 things I have been having a problem with is determining the position of the caret, and creating a new string with the value of the textarea before the carets positon + the code I'm inserting + the value of the textarea after the carets position.

推荐答案

我目前已经有了这个扩展名:

i've currently got this extension in place:

$.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);

这篇关于如何在textarea中的当前插入位置插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆