最后设置文本框的光标

时间:2018-07-10 15:03:46

标签: angular html5 typescript textbox chat

我需要为聊天消息创建一个用户输入表单。 因此,我使用以下HTML代码:

HTML-code

当用户按下ENTER键时,我将从文本框中获取文本并保存, 当用户按下CTRL + ENTER时,我添加“ \ n”以在下一行移动消息。

TypeScript-code

但是,当我按CTRL + ENTER时,光标将移动到输入字段的开头。

如何最终移动它?谢谢。

Cursor result

1 个答案:

答案 0 :(得分:1)

调用下面的函数setEndOfContenteditable($('.text-field'))

当前给定的代码使用Javascript,请转换为TypeScript

function setEndOfContenteditable(contentEditableElement) {
             var range,selection;
             if(document.createRange) { //Firefox, Chrome, Opera, Safari, IE 9+
                range = document.createRange();//Create a range (a range is a like the selection but invisible)
                range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
                range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                selection = window.getSelection();//get the selection object (allows you to change selection)
                selection.removeAllRanges();//remove any selections already made
                selection.addRange(range);//make the range you have just created the visible selection
              }
              else if(document.selection)//IE 8 and lower
              { 
                 range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
                 range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
                 range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                 range.select();//Select the range (make it the visible selection
            }
         }