Last active
November 5, 2025 02:35
-
-
Save xinglongjizi/9a769155a246d07b8c8cd6416fbcec4d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| <input | |
| type="number" | |
| min="0" | |
| step="1" | |
| @keydown="numberKeyDown" | |
| @change="numberChange" | |
| /> | |
| */ | |
| const numberKeyDown = async (e: KeyboardEvent) => { | |
| const pattern = /^[^\d]$/ | |
| if (pattern.test(e.key)) { | |
| e.preventDefault() | |
| } | |
| } | |
| const numberChange = (e: Event) => { | |
| const $this = e.target as HTMLInputElement | |
| if ($this.value) { | |
| $this.stepUp() | |
| $this.stepDown() | |
| } | |
| } | |
| /* | |
| 注意实现输入非数字字符时,禁止输入的功能,只能监听 keydown 事件 | |
| 因为,其他比如 keyup、inpuit 事件,字符已经输入进去了,已经生效了,再使用 e.preventDefault() 阻止默认行为已经晚了 | |
| 如果设置了最大值就 stepDown 再 stepUp | |
| 如果设置了最小值就 stepUp 再 stepDown | |
| 优化:支持N位小数 | |
| */ | |
| step = 0.0001 // 4位小数 | |
| // 再允许输入小数点 | |
| if (pattern.test(e.key) && e.key !== '.') { | |
| e.preventDefault() | |
| } | |
| /* | |
| setp设置成小数后,input会产生浏览器默认验证行为生成的title: “请输入有效值。两个最接近的有效值分别为...” | |
| 去掉此title的方法是自己写个title=" " 等于一个空格 | |
| 虽然step定义了几位小数,但是用户还是可以随意输入任意位的小数 | |
| 解决方式就是在change事件中执行 | |
| $this.stepUp() | |
| $this.stepDown() | |
| 先up再down的效果是截取多余位数的小数,比如 0.2222999 变成 0.2222 | |
| 拆解步骤就是: | |
| 输入: 0.1234111 | |
| up: 0.1235 | |
| down: 0.1234 | |
| 因此看起来是截取 | |
| $this.stepDown() | |
| $this.stepUp() | |
| 先down在up效果是ceil多余为的小数,比如 0.2222111 变成 0.2223 | |
| 拆解步骤就是: | |
| 输入: 0.1234111 | |
| down: 0.1234 | |
| up: 0.1235 | |
| 因此看起来是ceil | |
| */ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment