使用 JavaScript 将光标放在文本输入元素中文本的末尾

2022-08-29 23:36:51

在焦点设置为元素之后,通过JavaScript将光标放在输入文本元素中文本末尾的最佳方法(我推测是最简单的方法)是什么?


答案 1

有一种简单的方法可以让它在大多数浏览器中工作。

this.selectionStart = this.selectionEnd = this.value.length;

但是,由于一些浏览器的*怪癖,更具包容性的答案看起来更像这样

setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);

使用jQuery(设置监听器,但没有必要)

$('#el').focus(function(){
  var that = this;
  setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='el' type='text' value='put cursor at end'>

使用Vanilla JS(从这个答案借用addEvent函数)

// Basic cross browser addEvent
function addEvent(elem, event, fn){
if(elem.addEventListener){
  elem.addEventListener(event, fn, false);
}else{
  elem.attachEvent("on" + event,
  function(){ return(fn.call(elem, window.event)); });
}}
var element = document.getElementById('el');

addEvent(element,'focus',function(){
  var that = this;
  setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
});
<input id='el' type='text' value='put cursor at end'>

怪癖

Chrome有一个奇怪的怪癖,即焦点事件在光标移动到字段之前触发;这搞砸了我的简单解决方案。解决此问题的两个选项:

  1. 您可以添加 0 毫秒的超时(以延迟操作,直到堆栈清除)
  2. 您可以将事件从 更改为 。这对用户来说会很烦人,除非你仍然跟踪焦点。我并没有真正爱上这两个选项。focusmouseup

此外,@vladkras指出,一些旧版本的Opera在有空格时会错误地计算长度。为此,您可以使用一个应该大于字符串的大数字。


答案 2

试试这个,它对我有用:

//input is the input element

input.focus(); //sets focus to element
var val = this.input.value; //store the value of the element
this.input.value = ''; //clear the value of the element
this.input.value = val; //set that value back.  

要将光标移动到末尾,输入必须首先具有焦点,然后当值更改时,它将转到末尾。如果将 .value 设置为相同,则在 chrome 中它不会更改。