javascript - 将光标放在 keyup 上文本的末尾

标签 javascript html angular

我正在实现与命令行相同的功能。当您输入一些命令然后按下向上键按钮时,您将看到您之前的命令。

现在我已经完成了所有工作并且工作正常,但我遇到了一个小问题。

我现在遇到的问题是,按up键时,光标位于命令的开头,而使用down 按钮,光标位于命令的结尾

预期的行为是光标将放置在两者的末尾


这与其他问题有何不同?

  • 焦点已经在输入字段上。
  • 它确实适用于向下按钮

setTimeout(function() {
var inputs = document.querySelectorAll('input');

inputs[0].onkeydown = function(e){
  //keyup
  if(e.keyCode == 38) {
    inputs[inputs.length-1].value = 'up pressed';
  }
  
  if(e.keyCode == 40 ) {
      inputs[0].value = 'down pressed';
  }
}
}, 1000);
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <input type="text" placeholder="press the up or down key"/>
  </body>

</html>

最佳答案

setTimeout(function() {
var inputs = document.querySelectorAll('input');

inputs[0].onkeydown = function(e){
  //keyup
  if(e.keyCode == 38) {
    // placed here, it prevents the key's default behaviour to go at the end of the input text
    e.preventDefault();
    inputs[inputs.length-1].value = 'up pressed';
  }
  
  if(e.keyCode == 40 ) {
      inputs[0].value = 'down pressed';
  }

}
}, 1000);
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <input type="text" placeholder="press the up or down key"/>
  </body>

</html>

关于javascript - 将光标放在 keyup 上文本的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45764363/

相关文章:

html - 为什么是:hover slower than td:hover?

javascript - 删除列表中的最后一项

angular - 在主应用程序之外渲染 Angular 组件

javascript - 当我在 eclipse 中清理和构建 android 项目时,它会删除 bin 文件夹和 gen 文件夹并重新生成空的 gen 和 bin 文件夹

c# - 如何在 Razor 的部分 View 中获取 HTMLPREFIX

javascript - 所有 AJAX 异步请求完成事件?

javascript - 如何使用 ngStyle (angular2) 添加背景图像?

javascript - Angular 多步形式路由

node.js - Node JS/Angular 2 应用程序,ForbiddenError : invalid csrf token

JavaScript 正则表达式替换多个模式