javascript - 按下键时如何专注于输入?
问题描述
所以我正在为我叔叔制作这个英亩和克拉计算器的东西,我正在使用香草 javascript,当我按下键盘上的任何小键盘键时,我想专注于文本输入并在文本框中输入该数字,我已经在网上搜索了一个小时,但我找不到我想要的。
所以这就是它的样子。哦,我也忘了提到我想让点击动画在我按下键盘上的一个键时发生,但我不知道该怎么做。任何帮助将不胜感激,并提前感谢。
`
function onekey(event) {
if(event.keyCode === 1) {
input.focus();
input.value += 1;
}
}
`
<td><button id="one" onkeypress="onekey(event)">1</button></td>
解决方案
基本上你的问题是你在听数字按钮上的按键 - 你需要创建一个全局按键监听器来监听任何按键然后更新你的输入
const input = document.getElementById('input');
function listenForKeyPress() {
// add document event listener for all key presses
document.addEventListener('keyup', (e) => {
// check to see if the keypress was a number
if (/[0-9]/g.test(e.key)) {
// check to see if the input is not already focused
if (document.activeElement !== input) {
// focus element
input.focus();
// focus value
input.value += e.key;
}
}
})
}
// call function
listenForKeyPress();
<input id="input" type="number" />
如您所见,我们是
- 监听任何按键
- 使用正则表达式检查按键是否是 0 - 9 之间的数字
- 检查输入是否已经聚焦
- 如果输入尚未聚焦 - 聚焦输入并更新输入值
您现在可能会遇到的另一个问题是单击您的元素不会更新输入值,因此您可以执行此操作
function key(event) {
// get input
const input = document.getElementById('input');
// focus input
input.focus();
// update the value with the innerText of the clicked element - which is the number 1
input.value += event.toElement.innerText;
}
<input id="input" type="number" />
<button id="one" onclick="key(event)">1</button>
推荐阅读
- macos - 我可以使用智能文件夹的查找器项目计数作为触发器吗?
- salesforce - Salesforce REST API - 识别重复错误的来源
- angular - Ngb Typehead 结果与部分
- python - 当我尝试使用 plyfile API 访问 .ply 文件时,为什么会出现 ValueError:两个具有相同名称的属性?
- visual-studio - .NetCore 运行时标识符参数被忽略,MSBuild,Team City
- twitter - 确定状态/过滤端点的 Twitter API 速率限制
- cocoa - AVAudioBuffer 和 AVAudioFormat,将 interleaved 设置为 true 会产生零值样本数据
- spring - 我无法在嵌入式 Tomcat/Intellij 中调用我的 html 视图 - 带有 Thymeleaf 的 Springboot
- windows - PowerShell 中的 Echo 等效项
- autodesk-forge - 通过 Autodesk Forge Model Derivative 翻译后缺少属性字段