【问题标题】:Set mouse cursor at the end of the block of text在文本块的末尾设置鼠标光标
【发布时间】:2013-06-29 04:29:49
【问题描述】:

$(id).focus(); 将光标位置设置为输入框的开头,但我想将其放在文本的末尾、最后一行和最后一个位置。

【问题讨论】:

    标签: javascript jquery html focus


    【解决方案1】:

    您可以为此使用setSelectionRange

    我的代码 -

    HTML -

    <textarea rows="8" id="txt1" style="width:400px;" >Hello Hello Hello Hello</textarea>
    

    jquery -

    var input = $("#txt1");
    var len = input.val().length;
    input[0].focus();
    input[0].setSelectionRange(len, len);
    

    试试 -

    Example

    【讨论】:

    • 您也应该在此处发布您实际使用的代码,而不仅仅是一个jsFiddle
    【解决方案2】:

    试试这个:

    $(document).ready(function(){
            $("#search").focus(function(){
                if (this.setSelectionRange)
                {
                var len = $(this).val().length;
                this.setSelectionRange(len, len);
                }
                else
                {
                $(this).val($(this).val());
                }
    
        });
    
        $("#search").focus();
        });
    

    Demo with input

    Demo with textarea

    因为并非所有浏览器都支持setSelectionRange。所以最好的解决方案是将setSelectionRange$(this).val($(this).val());结合起来。欲了解更多信息,请查看:Use JavaScript to place cursor at end of text in text input element

    【讨论】:

    • 它在开始时设置位置,但我希望它在文本末尾
    • @nrsharma:查看演示。我用 Chrome 测试过,它可以工作
    • 它不适用于
    • @nrsharma:我认为问题出在浏览器上。 setSelectionRange Ishan Jain 的回答也是解决方案。但并非所有浏览器都支持setSelectionRange。我认为最好的方法是将这个解决方案与setSelectionRange
    • 好吧,你是对的 setSelectionRange 并不适用于所有浏览器。
    猜你喜欢
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    相关资源
    最近更新 更多