【问题标题】:JavaScript, add in string to text area based on cursor positionJavaScript,根据光标位置将字符串添加到文本区域
【发布时间】:2014-10-17 13:35:17
【问题描述】:

我目前有一个可以工作的系统。我想在用户回车时添加<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;
    }
});

Here's a JSfiddle 以上在行动 我知道当前的解决方案不适用于在当前光标位置添加 &lt;br /&gt; 标记。

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

    $("#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;
    }
});

不确定我是否以完全错误的方式进行操作,所以请随时提供替代解决方案或帮助我解决上面的部分伪代码?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

这里是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/

【讨论】:

    【解决方案2】:

    Tim Down 回答了这个问题:

    How do I insert some text where the cursor is?

    它应该完全符合您的需求。只需将其称为按键处理的一部分即可。

    【讨论】:

      猜你喜欢
      • 2011-03-31
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2010-09-25
      相关资源
      最近更新 更多