且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript输入只允许数字

更新时间:2023-02-21 12:17:30

如果您使用 HTML5 很酷,并且只针对现代浏览器,新属性必需模式随时为您服务。示例:

If you're cool in using HTML5 and only target modern browsers, the new attributes required and pattern are here for you. Example:

<input id="txtChar" type="number" required pattern="\d+"/>

您可以通过 CSS 来解决状态

#txtChar:required:valid {
    border: 1px solid green;
}

#txtChar:required:invalid {
    border: 1px solid red;
}

如果在< form>中使用标记,用户将无法以无效状态提交。

If used within a <form> tag, a user won't be able to submit in invalid state.

我刚看到你无法访问标记,所以道歉。我将把它留作信息性答案。