什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过JavaScript -焦点已设置到元素?


当前回答

我已经尝试了以下相当大的成功在chrome

$("input.focus").focus(function () {
    var val = this.value,
        $this = $(this);
    $this.val("");

    setTimeout(function () {
        $this.val(val);
    }, 1);
});

简单介绍一下:

它获取每个带有类焦点的输入字段,然后将输入字段的旧值存储在一个变量中,然后将空字符串应用于输入字段。

然后等待1毫秒,再次输入旧值。

其他回答

下面是我的答案的jsFiddle演示。演示使用CoffeeScript,但如果需要,可以将其转换为纯JavaScript。

JavaScript中重要的部分是:

var endIndex = textField.value.length;
if (textField.setSelectionRange) {
   textField.setSelectionRange(endIndex, endIndex);
}

我把这个答案贴出来是因为我已经为有同样问题的其他人写过了。这个答案不像上面的答案那样涵盖那么多的边缘情况,但它适合我,并且有一个jsFiddle演示可以玩。

下面是来自jsFiddle的代码,所以即使jsFiddle消失了,这个答案也会被保留:

moveCursorToEnd = (textField) ->
  endIndex = textField.value.length
  if textField.setSelectionRange
    textField.setSelectionRange(endIndex, endIndex)

jQuery ->
  $('.that-field').on 'click', ->
    moveCursorToEnd(this)
<div class="field">
    <label for="pressure">Blood pressure</label>:
    <input class="that-field" type="text" name="pressure" id="pressure" value="24">
</div>
<p>
    Try clicking in the text field. The cursor will always jump to the end.
</p>
body {
    margin: 1em;
}

.field {
    margin-bottom: 1em;
}
<script type="text/javascript">  
    function SetEnd(txt) {  
      if (txt.createTextRange) {  
       //IE  
       var FieldRange = txt.createTextRange();  
       FieldRange.moveStart('character', txt.value.length);  
       FieldRange.collapse();  
       FieldRange.select();  
       }  
      else {  
       //Firefox and Opera  
       txt.focus();  
       var length = txt.value.length;  
       txt.setSelectionRange(length, length);  
      }  
    }   
</script>  

我在IE9和Firefox 6中使用了这个功能。和Opera 11.x

简单。在编辑或更改值时,首先放置焦点,然后设置值。

$("#catg_name").focus();
$("#catg_name").val(catg_name);

document.querySelector(“输入”)。addEventListener('focus', e => { Const {value} = e.target; e.target.setSelectionRange(价值。长度,value.length); }); <input value="my text" />

var valsrch = $('#search').val();
$('#search').val('').focus().val(valsrch);