Javascript:将插入符移动到最后一个字符
我有一个文本区域,当我单击它时,我想将插入符号移动到最后一个字符,所以 Something[caret]
function moveCaret(){
// Move caret to the last character
}
<textarea onclick="moveCaret();">
Something
</textarea>
据我所知,这在某种程度上可以通过 TextRange 对象实现,但我真的不知道知道如何使用它
编辑:我希望只看到纯JavaScript解决方案,所以不要使用库。
I have a textarea and when I click in it I want to move the caret to the last character so Something[caret]
function moveCaret(){
// Move caret to the last character
}
<textarea onclick="moveCaret();">
Something
</textarea>
As I know this is somehow possible with the TextRange object, but I don't really know how to use it
EDIT: I would love to see only pure javascript solutions so no libraries please.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下函数适用于所有主要浏览器,适用于文本区域和文本输入:
但是,每当用户单击文本区域时,您确实不应该执行此操作,因为用户将无法使用鼠标移动插入符号。相反,当文本区域获得焦点时执行此操作。 Chrome 中也存在一个问题,可以按如下方式解决:
完整示例: http://www .jsfiddle.net/ghAB9/3/
HTML:
脚本:
The following function will work in all major browsers, for both textareas and text inputs:
However, you really shouldn't do this whenever the user clicks on the textarea, since the user will not be able to move the caret with the mouse. Instead, do it when the textarea receives focus. There is also a problem in Chrome, which can be worked around as follows:
Full example: http://www.jsfiddle.net/ghAB9/3/
HTML:
Script: