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

前端 未结 1 554
深忆病人
深忆病人 2020-12-05 12:45

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.

This is the

相关标签:
1条回答
  • 2020-12-05 12:55

    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
            }
        });
    };
    

    and you can use it like so:

    $("#txtPost").insertAtCaret(ch);
    
    0 讨论(0)
提交回复
热议问题