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


当前回答

好吧,我只用:

$("#myElement").val($("#myElement").val());

其他回答

下面是我的答案的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;
}

我刚在iOS中发现,设置textarea。textContent属性每次都会将光标放在textarea元素中文本的末尾。这种行为是我的应用程序中的一个bug,但似乎是你可以故意使用的东西。

如果输入字段只需要一个静态默认值,我通常用jQuery这样做:

$('#input').focus().val('Default value');

这似乎在所有浏览器中都有效。

var valsrch = $('#search').val();
$('#search').val('').focus().val(valsrch);
<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