JavaScript,根据光标位置将字符串添加到文本区域
我目前有一个这样的系统。我想在用户点击enter时添加JavaScript,根据光标位置将字符串添加到文本区域,javascript,jquery,Javascript,Jquery,我目前有一个这样的系统。我想在用户点击enter时添加 目前,它的工作方式是抓取文本区的当前内容,将附加到文本区,然后将全部内容输出回文本区。因此,这是可行的,但只会在内容末尾添加 $("#postcontent").keypress(function(e) { // If enter key pressed if(e.which == 13) { var currentHTML = document.getElementById("postcontent
目前,它的工作方式是抓取文本区的当前内容,将
附加到文本区,然后将全部内容输出回文本区。因此,这是可行的,但只会在内容末尾添加
$("#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;
}
});
$(“#后内容”)。按键(功能(e){
//如果按enter键
如果(e.which==13){
var currentHTML=document.getElementById(“postcontent”).value;
var currentHTML=currentHTML+“\n
”
document.getElementById(“postcontent”).value=currentHTML;
}
});
上述措施的作用
我知道当前解决方案无法在当前光标位置添加
标记
我在想这样的事情,但不知道怎么处理
$("#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;
}
});
$(“#后内容”)。按键(功能(e){
//如果按enter键
如果(e.which==13){
//找到光标的位置
//抓取光标前的所有内容并存储在var contentBefore中
//抓取光标后的所有内容并存储在var contentAfter中
document.getElementById(“postcontent”).value=contentBefore+“
”+contentAfter;
}
});
我不确定我是不是完全错了,所以请提供其他解决方案或帮助我解决上面的部分伪代码?Tim Down对这个问题有一个答案: 它应该完全符合你的需要。这只是你按键操作的一部分 以下是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 );
}
});
});
$(文档).ready(函数(){
$(“#后内容”)。按键(功能(e){
如果(e.which==13){
//var currentHTML=document.getElementById(“postcontent”).value;
//var currentHTML=currentHTML+“\n
”
//document.getElementById(“postcontent”).value=currentHTML;
var cursorPos=$('#postcontent').prop('selectionStart'),
v=$(“#后内容”).val(),
textBefore=v.substring(0,游标),
textfafter=v.substring(cursorPos,v.length);
$(“#后内容”).val(textBefore+”
“+textAfter);
}
});
});
我想您正在寻找“文本区域中的插入符号位置”,也许这会有所帮助