【发布时间】: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 以上在行动
我知道当前的解决方案不适用于在当前光标位置添加 <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;
}
});
不确定我是否以完全错误的方式进行操作,所以请随时提供替代解决方案或帮助我解决上面的部分伪代码?
【问题讨论】:
-
我认为您正在寻找“文本区域中的插入符号位置”,也许这会有所帮助stackoverflow.com/questions/263743/…
标签: javascript jquery