[英]Cursor position in textarea on click
I am working on a little emoji function. 我正在开发一个表情符号功能。 My problem is when I have a text in the textarea and select an emoji from the drop down it always goes to the end of the text even if I place the cursor at the beginning of the text, the emoji will go to the end of the text like so:
我的问题是,当我在文本区域中有一个文本并从下拉列表中选择一个表情符号时,即使将光标放在文本的开头,该表情符号也始终会移到文本的结尾,该表情符号会转到文本的结尾像这样的文字:
Some text here 😃 一些文字here
The code: 编码:
function insertSmiley(smiley)
{
var currentText = document.getElementById("textarea");
var smileyWithPadding = " " + smiley + " ";
currentText.value += smileyWithPadding;
currentText.focus();
}
I tried to remove currentText.focus();
我试图删除
currentText.focus();
but it didn't help. 但这没有帮助。 I also tried to use jQuery to keep the textarea's focus but the emoji would still go to the end of the text:
我也尝试使用jQuery来保持文本区域的焦点,但表情符号仍会到达文本的结尾:
$(window).load(function(){
var lastFocus;
$("#dropdown-emojis").mousedown(function(e) {
return false;
});
});
How can I make the emoji to show at the place where I place the cursor? 如何使表情符号显示在放置光标的地方?
use .selectionStart and .selectionEnd to know where the cursor is. 使用.selectionStart和.selectionEnd知道光标在哪里。
var startPosition = myElement.selectionStart;
var endPosition = myElement.selectionEnd;
if(startPosition == endPosition){
newString= currentText.value.substring(0,startPosition)+ " " + smiley + " " + currentText.value.subString(endPosition,currentText.value.lenght());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.