gpt4 book ai didi

css - 输入类型 ="number"模式 ="[0-9]*"允许 firefox 中的字母

转载 作者:太空狗 更新时间:2023-10-29 13:42:27 24 4
gpt4 key购买 nike

所以,所有问题都在主题的标题中。使用 pattern="[0-9]*" 输入 type="number" 在 Chrome 中工作正常,但在 FF 中允许字母。有什么方法可以不使用 jQuery 或 JS 来修复它吗?

.small-input {
-moz-appearance: textfield;
}
.small-input::-webkit-inner-spin-button {
display: none;
}

.small-input::-webkit-outer-spin-button,
.small-input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
}
<input class="small-input " pattern="[0-9]*" value="" type="number">

最佳答案

您可以使用 Regex 来完全阻止用户在 input 字段中输入任何字母。

所以我会在您的输入元素上添加以下事件监听器:onkeypress="preventNonNumericalInput(event)"

<input class="small-input " pattern="[0-9]*" value="" type="number" onkeypress="preventNonNumericalInput(event)">

然后在您的 JavaScript 文件中创建以下函数:

function preventNonNumericalInput(e) {
e = e || window.event;
var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
var charStr = String.fromCharCode(charCode);

if (!charStr.match(/^[0-9]+$/))
e.preventDefault();
}

我已经对此进行了测试,它应该可以防止任何非数字输入和任何特殊字符,例如 @#./? 等...

关于css - 输入类型 ="number"模式 ="[0-9]*"允许 firefox 中的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49923588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com