以编程方式添加文本后如何在输入中显示文本结尾?

How to show end of the text in input after programmatically adding text?

我想以编程方式在输入中添加单词并始终看到文本的末尾。但问题是,当我添加单词(如 input.value += 'word')时,当文本长度几乎与输入长度相同时,输入中的文本不会移动,所以我只能看到文本的开头和结局被隐藏了。
我认为如果我可以将光标放在输入的末尾会有帮助,但是 none 的光标技巧在 Chrome 中不起作用,例如

input.value = input.value

input.setSelectionRange(input.value.length, input.value.length);

如果输入没有焦点,那么 Chrome 会一直向左显示 "scrolled",显示输入值的开头。

如果元素有焦点,则可以设置选择范围移动光标:

window.onload = function(){
  
  var input = document.getElementById('foobar');
  input.value += ' bazbat';
  
  input.focus();
  input.setSelectionRange( input.value.length - 1 );
  
}
<input id="foobar" value="foobar" size="6">

但如果在用户尝试键入值时光标四处移动,这将是一个非常混乱和令人沮丧的用户体验。

要考虑的其他选项:

  • 更改输入的宽度以匹配值。 make html text input field grow as I type?
  • 在输入和范围之间切换(编辑模式与读取模式)。使用跨度,您可以更好地控制文本的显示方式。 Jquery: Toggle between input and text on click
  • 使用某种指示器来提醒用户他们的输入值之一已被修改。即使他们可以看到整个值,这也会很有用,因为他们可能不会注意到该值已更新。

似乎工作得很好:

let input = document.getElementById('auto');
let sentence = 'Courage is the magic that turns dreams into reality.';
let index = 0;

setTimeout(function typing() {
  let letter = sentence.charAt(index++);

  input.blur();
  input.value += letter;
  input.focus();
  input.setSelectionRange(index, index);

  if (index < sentence.length) {
    let ms = Math.floor(75 + Math.random() * 150);

    setTimeout(typing, ms);
  }
}, 1000);
<input id="auto" type="text">