将光标移动到最后一个输入

时间:2017-08-12 17:35:01

标签: jquery html cursor

我有一个textarea,用户可以在其中输入文字。用户还可以按下按钮添加图像和链接等内容。此按钮即提示他们输入链接,然后在光标所在的textarea 中输入正确的html 。一个有效的代码示例如下:

jQuery('input#btn').click(function(e) {
    var link = prompt("Please paste the link", "http://");
    jQuery('textarea#id1').insertAtCaret('<a href="'+link+'">link text</a>');
});

.insertAtCaret()函数是Daniel Beck for another question of mine创建的函数。它在textarea中找到光标的位置,这样就可以在这里添加html块。

但是在jQuery添加了这个html-chunk之后,光标不再在textarea中了,但是现在焦点放在按下的按钮上。我希望光标在按下此按钮之前保持原样(在添加的html块之后)。

是否可以在textarea中找到最后输入的文本,然后可以将光标移动到那里?

请注意,此输入可以是textarea中已写入文本中的任何位置。

1 个答案:

答案 0 :(得分:1)

首先,您必须将焦点放回文本区域。

var te = document.getElementById('id1');
te.focus();

然后将光标设置到特定位置。

var mySavedPosition = 3 // or whatever it was before
te.selectionStart = mySavedPosition;
te.selectionEnd = mySavedPosition;

多数民众赞成。

所以在你的例子中它可能看起来像这样:

jQuery('input#btn').click(function(e) {
    var link = prompt("Please paste the link", "http://");
    var te = document.getElementById('id1');
    var pos = te.selectionStart;
    jQuery('textarea#id1').insertAtCaret('<a href="'+link+'">link text</a>');
    te.selectionStart = pos;
    te.selectionEnd = pos;
});

抱歉,但我不是jQuery的朋友,所以我只使用原生JS。

更新

我忽略了你想把光标放在插入位置的末尾。由于我不知道插入文本的长度,我最好从最后得到位置。

jQuery('input#btn').click(function(e) {
    var link = prompt("Please paste the link", "http://");
    var te = document.getElementById('id1');
    var pos = te.textLength - te.selectionStart;
    jQuery('textarea#id1').insertAtCaret('<a href="'+link+'">link text</a>');
    te.selectionStart = te.textLength - pos;
    te.selectionEnd = te.textLength - pos;
});
相关问题