JavaScript,根据光标位置将字符串添加到文本区域

JavaScript, add in string to text area based on cursor position

本文关键字:添加 字符串 文本 区域 位置 光标 JavaScript      更新时间:2023-09-26

我目前有一个可以工作的系统。我想在用户点击回车键时添加<br />

目前,它的工作方式是获取文本区域的当前内容,将<br />附加到其中,然后将整个批次输出回来。因此,这是有效的,但只是将<br />添加到内容的末尾。

    $("#postcontent").keypress(function(e) {
    // If enter key pressed
    if(e.which == 13) {
        var currentHTML = document.getElementById("postcontent").value;
        var currentHTML = currentHTML + "'n<br /><br />"
        document.getElementById("postcontent").value = currentHTML;
    }
});

这是上面的一个动作我知道当前的解决方案不适用于在当前光标位置添加<br />标记。

我在想这样的事情,但不确定如何处理。

    $("#postcontent").keypress(function(e) {
    // If enter key pressed
    if(e.which == 13) {
        // Find the location of the cursor
        // Grab all the content BEFORE the cursor and store in var contentBefore
        // Grab all the content AFTER the cursor and store in var contentAfter
        document.getElementById("postcontent").value = contentBefore + "<br /><br />"  + contentAfter;
    }
});

不确定我的做法是否完全错误,所以请随时提供替代解决方案或帮助我计算上面的伪代码部分?

以下是jQuery方式:

$(document).ready(function(){
    $("#postcontent").keypress(function(e) {
    if(e.which == 13) {
        //var currentHTML = document.getElementById("postcontent").value;
        //var currentHTML = currentHTML + "'n<br /><br />"
        //document.getElementById("postcontent").value = currentHTML;
    var cursorPos = $('#postcontent').prop('selectionStart'),
    v = $('#postcontent').val(),
    textBefore = v.substring(0,  cursorPos ),
    textAfter  = v.substring( cursorPos, v.length );
    $('#postcontent').val( textBefore+ "<br />" +textAfter );

    }
});
});

http://jsfiddle.net/o9jaatak/1/

Tim Down对这个问题有一个答案:

如何在光标所在的位置插入一些文本?

它应该完全符合你的需要。只需将其作为按键处理的一部分。