我只想记住textarea中的最后一个位置,但我总是失败。
我有这段代码:
//This function catch the position
(function ($, undefined) {
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
} else if('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
//Insert the text by clicking an icon
function insertar(texto) {
var div = $('textarea');
var text = div.val();
var pos = div.getCursorPosition();
text = text.substring(0,pos) + " " + texto + text.substring(pos);
div.val(text);
}
$('#icon').click(function(evt){ insertar(':icon:'); });
好吧,如果我写这个:
“你好你好”
我想用函数添加它:
“嗨嗨你好,你好”
它给了我这个:
“嗨,你好,你好。”
我认为第二次执行该功能时,会忘记位置并在文本末尾添加文本。
PD:我正在添加单击图像的文本。我正在尝试为论坛做一个快速回复的字段集。
任何人都知道问题在哪里?
以下是我可以看到它的演示:http://jsfiddle.net/ko295zpw/6/
答案 0 :(得分:1)
一个选项是设置一个bool,用于确定是否需要重新找到光标位置,然后在每次点击textarea
时将bool重置为true,并在&#后将其设置为false 39;用户点击textarea
后第一次找到该位置。您需要将var pos
和bool的声明移动到insertar
函数之外的范围。所以:
var encontrarPos = true;
var pos = 0;
function insertar(texto) {
var div = $('textarea');
var text = div.val();
if (encontrarPos) pos = div.getCursorPosition();
encontrarPos = false;
console.log(pos);
text = text.substring(0,pos) + texto + " " + text.substring(pos);
div.val(text);
}
$('textarea').click(function() {
encontrarPos = true;
});
这里有更新的Fiddle