文本框中最后一个字符后设置焦点

74

我有3个文本框用于输入电话号码。当用户输入时,它会自动移动到下一个文本框。当用户按退格键时,我可以将焦点移动到前一个文本框。问题是,在IE中,焦点会设置在文本框的开头。这是我的代码,在Chrome中运行良好。

$('#AreaCode').live('keyup', function (event) {
    if ($(this).val().length == $(this).attr("maxlength"))
        $('#Prefix').focus();
});

$('#Prefix').live('keyup', function (event) {
    if (event.keyCode == 8 && $(this).val().length == 0)
        $('#AreaCode').focus();

    if ($(this).val().length == $(this).attr("maxlength"))
        $('#Number').focus();
});

$('#Number').live('keyup', function (event) {
    if (event.keyCode == 8 && $(this).val().length == 0)
        $('#Prefix').focus();
});

向后移动焦点时如何使其定位在内容的末尾?


1
请将光标放在文本输入元素的末尾,使用JavaScript进行操作。 - Alex Vidal
另一种简单的方法在这里:https://dev59.com/jmIk5IYBdhLWcg3wIq5U#19568146 - shim
10个回答

99

这是一种简单的方法。如果你需要向后兼容,只需在设置焦点之后添加$("#Prefix").val($("#Prefix").val());

这是更加适当(干净)的方式:

function SetCaretAtEnd(elem) {
        var elemLen = elem.value.length;
        // For IE Only
        if (document.selection) {
            // Set focus
            elem.focus();
            // Use IE Ranges
            var oSel = document.selection.createRange();
            // Reset position to 0 & then set at end
            oSel.moveStart('character', -elemLen);
            oSel.moveStart('character', elemLen);
            oSel.moveEnd('character', 0);
            oSel.select();
        }
        else if (elem.selectionStart || elem.selectionStart == '0') {
            // Firefox/Chrome
            elem.selectionStart = elemLen;
            elem.selectionEnd = elemLen;
            elem.focus();
        } // if
    } // SetCaretAtEnd()

不是 Carat 而是 Caret。我还用 try..catch 包装了它,以防万一,并在开头加入了 "if (elemLen == 0) { return; }"。此外,你的代码第一行的格式与其余部分不同。除此之外,感谢你的代码 :) - Anthony
1
感谢您纠正我的拼写/格式错误。我已更新我的回答以进行修复。很高兴它对您有用。 - ChrisG
4
在第2行的var elemLen = elem.value.length;之前,我添加了elem = $(elem).get(0);。如果对象是一个jQuery对象,它将被转换为javascript对象。如果它已经是javascript对象,这一行将不会做任何事情,因为一切都没问题 :)这一行避免了“elem.value未定义”的错误。 - ReynekeVosz
对我有用 - 值得一提的是,为了提高效率,您应该将焦点链接到val的末尾。 - Liath
你从 https://exceptionshub.com/set-focus-after-last-character-in-text-box.html 复制了这段代码吗? - jasinth premkumar

55

我尝试了许多不同的解决方案,只有基于此页面上Chris G的解决方案(稍作修改)的解决方案适用于我。

我将其转化为jQuery插件,以便将来任何需要它的人可以使用。

(function($){
    $.fn.setCursorToTextEnd = function() {
        var $initialVal = this.val();
        this.val($initialVal);
    };
})(jQuery);

使用示例:

$('#myTextbox').setCursorToTextEnd();

2
+1 为将其制作成插件而感到高兴。在调用此函数之前,请记得对元素调用 focus() - flu
2
这在IE中似乎无法正常工作,只有在FF中可以。在IE中,它会回到文本的开头。还有其他人遇到这个问题吗? - Paolo Broccardo
2
为什么JavaScript变量前面要加美元符号?同时,使用“var”进行声明。 - Mathias Lykkegaard Lorenzen
3
在某些情况下,将美元符号放在jQuery变量前面是一种推荐的做法,以区分jQuery变量和普通JS变量。但在这种情况下完全没有必要这样做,因为该变量仅在函数范围内可用,显然是一个jQuery函数。 - user1428660
7
@gavin-g 很棒的插件。为了更好地跨浏览器兼容性,建议进行一次更新。可以先清空值再设置初始值,即 this.val('').val(initialVal); - Bradmage
显示剩余2条评论

50

这对我来说很好用。【参考:Gavin G的非常好的插件】

(function($){
    $.fn.focusTextToEnd = function(){
        this.focus();
        var $thisVal = this.val();
        this.val('').val($thisVal);
        return this;
    }
}(jQuery));

$('#mytext').focusTextToEnd();

2
@Gavin G的版本对我没用,但这个可以。 - Luis Rivera

27

你应该像这样编写代码。

var num = $('#Number').val();        
$('#Number').focus().val('').val(num);    

21

适用于任何浏览器的代码:

function focusCampo(id){
    var inputField = document.getElementById(id);
    if (inputField != null && inputField.value.length != 0){
        if (inputField.createTextRange){
            var FieldRange = inputField.createTextRange();
            FieldRange.moveStart('character',inputField.value.length);
            FieldRange.collapse();
            FieldRange.select();
        }else if (inputField.selectionStart || inputField.selectionStart == '0') {
            var elemLen = inputField.value.length;
            inputField.selectionStart = elemLen;
            inputField.selectionEnd = elemLen;
            inputField.focus();
        }
    }else{
        inputField.focus();
    }
}

尝试了很多答案后,终于成功了... :) 我正在使用IE 8。 - Diganta

13

可以在输入标签内使用这些简单的JavaScript代码。

<input type="text" name="your_name" value="your_value"
     onfocus="this.setSelectionRange(this.value.length, this.value.length);" 
autofocus />

12

您可以按照以下方式将指针设置在文本框的最后位置。

temp=$("#txtName").val();
$("#txtName").val('');
$("#txtName").val(temp);
$("#txtName").focus();

2
var val =$("#inputname").val();
$("#inputname").removeAttr('value').attr('value', val).focus();
// I think this is beter for all browsers...

1
<script type="text/javascript">
    $(function(){
        $('#areaCode,#firstNum,#secNum').keyup(function(e){
            if($(this).val().length==$(this).attr('maxlength'))
                $(this).next(':input').focus()
        })
    })
    </script>

<body>

<input type="text" id="areaCode" name="areaCode" maxlength="3" value="" size="3" />- 
<input type="text" id="firstNum" name="firstNum" maxlength="3" value="" size="3" />- 
<input type="text" id="secNum" name=" secNum " maxlength="4" value="" size="4" />

</body>

1

Chris Coyier开发了一个小型的jQuery插件,可以完美地实现此功能:http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/

如果支持,它使用setSelectionRange,否则有一个可靠的备用方案。

jQuery.fn.putCursorAtEnd = function() {
  return this.each(function() {
    $(this).focus()
    // If this function exists...
    if (this.setSelectionRange) {
      // ... then use it (Doesn't work in IE)
      // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
      var len = $(this).val().length * 2;
      this.setSelectionRange(len, len);
    } else {
      // ... otherwise replace the contents with itself
      // (Doesn't work in Google Chrome)
      $(this).val($(this).val());
    }
    // Scroll to the bottom, in case we're in a tall textarea
    // (Necessary for Firefox and Google Chrome)
    this.scrollTop = 999999;
  });
};

然后你只需要这样做:

input.putCursorAtEnd();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接