【问题标题】:How to show end of the text in input after programmatically adding text?以编程方式添加文本后如何在输入中显示文本的结尾?
【发布时间】:2016-09-29 15:58:46
【问题描述】:

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

input.value = input.value

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

【问题讨论】:

标签: javascript


【解决方案1】:

似乎工作得很好:

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);
&lt;input id="auto" type="text"&gt;

【讨论】:

    【解决方案2】:

    如果输入没有焦点,那么 Chrome 将显示它一直“滚动”到左侧,显示输入值的开头。

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

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

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

    要考虑的其他选项:

    【讨论】:

    • 示例现已损坏。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多