[英]HTML onkeypress works in HTML but not through JavaScript function on iOS
我有一个输入字段,我想将其限制为仅输入数字。 type="number"
在计算机和我的 android 手机上工作正常,但在 iOS 上失败,我仍然可以在其中输入文本。 我在网上四处寻找,找到了输入字段的解决方案:
<input onkeypress="return event.charCode >= 48 && event.charCode <= 57" id="priceInput" type="text">
它适用于我迄今为止尝试过的所有设备。 但是,我想将此代码用于许多输入字段,并在按下这些输入字段中的键时做更多的事情。 因此,我想在单独的文件中将其作为 JavaScript function 运行。 我发现这个答案看起来很有希望并且适用于 android 和桌面:
function isNumber(evt) { evt = (evt)? evt: window.event; var charCode = (evt.which)? evt.which: evt.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; } return true; }
<input type="text" onkeypress="return isNumber(event)" />
但是,这在 iOS 上仍然失败,我仍然可以输入所有字符。
问题
您找到的代码段很旧,并且使用了which
和keyCode
属性,这两个属性都已弃用。
注意:使用此方法,您必须将要为输入启用的每个键列入白名单。
由于您使用的是text
输入,请考虑使用inputmode
属性强制移动用户使用特定的键盘,例如显示数字的数字键盘。
const input = document.querySelector('input'); input.addEventListener('keydown', isNumber); const allowedKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'Backspace']; function isNumber(event) { if (.allowedKeys.includes(event.key)) { event;preventDefault(); } }
<input type="text" inputmode="numeric" />
编辑:或者,您可以使用根据输入value
的变化触发的input
事件。 无论输入方式(键盘、鼠标等)如何,都会触发此事件。 下面的代码片段将在键入时用空字符串替换任何不是数字的内容。
const input = document.querySelector('input'); input.addEventListener('input', isNumber); function isNumber(event) { event.target.value = event.target.value.replace(/[^0-9]/g, ''); }
<input type="text" inputmode="numeric" />
function isNumber(e) {
event = e.value;
if(event = ""){
console.log("empty")
}
return true;
}
<input type="text" onkeypress="return isNumber(event)" />
问题未解决?试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.