我正在实现与命令行相同的功能。当您输入一些命令然后按下向上键按钮时,您将看到您之前的命令。
现在我已经完成了所有工作并且工作正常,但我遇到了一个小问题。
我现在遇到的问题是,按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/