JavaScript,根据光标位置将字符串添加到文本区域
JavaScript, add in string to text area based on cursor position
我目前有一个可以工作的系统。我想在用户点击回车键时添加<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对这个问题有一个答案:
如何在光标所在的位置插入一些文本?
它应该完全符合你的需要。只需将其作为按键处理的一部分。
相关文章:
- 在 JS 中添加字符串之前强制换行
- javascript在动态Url中匹配并添加字符串
- 添加字符串+选择要输入的文本
- 通过向动态id添加字符串,使用JavaScript控制文本框
- 在哪里添加字符串原型
- 在 JavaScript 中添加字符串 “1” + - “2” == “1-2”
- 如何在javascript中的数组中添加字符串
- 如何在javascript/jquery中添加字符串美元金额
- 引用变量,它执行函数,但是向变量中添加字符串,将函数作为字符串而不是值返回
- 如何在 javaScript 中添加 C# 字符串作为文本弹出窗口
- AngularsJS JavaScript 匹配单词并添加字符串
- 使用 javascript 在括号内添加字符串
- 使用javascript进行大写,每隔换行一次,并在每一新行的开头添加字符串
- jQuery添加字符串而不是串联
- 正在向提交的URL末尾添加字符串
- 可以't使用concat添加字符串数组
- 如何自动添加字符串“;http://'当用户通过jquery在文本框中输入时
- jquery问题——向动态调用的元素添加字符串
- MVC 5 DropDownList向Jquery的值添加字符串
- 如何在单击链接/过滤器的基础上向onclick函数添加字符串?