js实现文本框只能输入数字包括负数和小数
时间: 2023-03-19 09:25:15 浏览: 100
您可以使用JavaScript编写一个函数来实现文本框只能输入数字,包括负数和小数。以下是一个简单的实现示例:
```javascript
function onlyNumber(event) {
// 允许的字符为数字、小数点和负号
const allowedChars = /[0-9.-]/;
// 获取输入的字符
const inputChar = String.fromCharCode(event.keyCode);
// 检查输入字符是否允许
if (!allowedChars.test(inputChar)) {
event.preventDefault();
}
// 检查小数点或负号是否已经存在
const input = event.target.value;
const hasDecimal = input.includes('.');
const hasMinus = input.includes('-');
if (inputChar === '.') {
if (hasDecimal || hasMinus) {
event.preventDefault();
}
} else if (inputChar === '-') {
if (hasMinus || input !== '') {
event.preventDefault();
}
}
}
```
您可以将上述函数与`onkeydown`事件一起使用,如下所示:
```html
<input type="text" onkeydown="onlyNumber(event)">
```
此函数的工作原理如下:
- 首先,定义一个允许的字符集合,只包含数字、小数点和负号。
- 然后,获取用户输入的字符,并检查它是否包含在允许的字符集合中。如果不是,阻止默认行为。
- 接下来,检查小数点或负号是否已经存在。如果是小数点并且已经存在,或者如果是负号并且已经存在或输入框中已经有了任何字符,则阻止默认行为。
请注意,这只是一个简单的示例,您可以根据自己的需求进行修改和定制。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)