在文本区域中的光标位置之后插入文本

Cap*_*mic 11 javascript jquery textarea

下面的脚本将文本插入文本区域的末尾.我需要更改为在文本区域中当前光标位置之后插入文本.

jQuery(document).ready(function($){
    $('#addCommentImage').click(function(){
        var imageLoc = prompt('Enter the Image URL:');
        if ( imageLoc ) {
            $('#comment').val($('#comment').val() + '[img]' + imageLoc + '[/img]');
        }
        return false;
    });
});
Run Code Online (Sandbox Code Playgroud)

d.p*_*pov 22

如果以上不起作用(在我的情况下不是 - 可能我的配置有点不同),这是另一个解决方案:

您可以使用此扩展功能获取位置:

(function ($, undefined) {
    $.fn.getCursorPosition = function () {
        var el = $(this).get(0);
        var pos = 0;
        if ('selectionStart' in el) {
            pos = el.selectionStart;
        } else if ('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

用法是: var position = $("#selector").getCursorPosition()

在该位置插入文字:

var content = $('#selector').val();
var newContent = content.substr(0, position) + "text to insert" + content.substr(position);
$('#selector').val(newContent);
Run Code Online (Sandbox Code Playgroud)

就这样.


Dar*_*rov 14

你可以查看这个答案.该insertAtCaretjQuery插件看起来非常漂亮.

  • 实际上链接到一个不起作用的版本.上面的那个是你想要的.这是小提琴http://jsfiddle.net/rmDzu/2/ (5认同)