Javascript:将插入符号移动到最后一个字符 [英] Javascript: Move caret to last character

查看:471
本文介绍了Javascript:将插入符号移动到最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个textarea,当我点击它,我想移动插入符到最后一个字符所以 Something [caret]



<$ class $ function moveCaret(){
//将光标移动到最后一个字符
}



 < textarea onclick =moveCaret > 
某事
< / textarea>

我知道这是有可能的TextRange对象,但我真的不知道如何使用它



编辑:我只想看到纯javascript解决方案,所以没有图书馆。

解决方案

以下函数将在所有主要浏览器中对textareas和文本输入工作:

  function moveCaretToEnd(el){
if(typeof el.selectionStart ==number){
el.selectionStart = el.selectionEnd = el.value.length;
} else if(typeof el.createTextRange!=undefined){
el.focus();
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}

但是,你真的不应该用户点击textarea,因为用户将无法使用鼠标移动插入符。相反,当textarea接收焦点时。在Chrome中也有一个问题,可以按如下方式处理:



完整示例:http://www.jsfiddle.net/ghAB9/3/



HTML:

 < textarea id =test> Something< / textarea> 

脚本:

  var textarea = document.getElementById(test); 
textarea.onfocus = function(){
moveCaretToEnd(textarea);

//解决Chrome的小问题
window.setTimeout(function(){
moveCaretToEnd(textarea);
},1);
};


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.

解决方案

The following function will work in all major browsers, for both textareas and text inputs:

function moveCaretToEnd(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}

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:

<textarea id="test">Something</textarea>

Script:

var textarea = document.getElementById("test");
textarea.onfocus = function() {
    moveCaretToEnd(textarea);

    // Work around Chrome's little problem
    window.setTimeout(function() {
        moveCaretToEnd(textarea);
    }, 1);
};

这篇关于Javascript:将插入符号移动到最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆