繁体   English   中英

如何在textarea中的当前插入位置插入文本

[英]How to insert text at the current caret position in a textarea

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

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

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

    }); 

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

我目前有这个扩展到位:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM