我有这样的 HTML 代码:
<input type="number" step="0.1" class="form-group">
Run Code Online (Sandbox Code Playgroud)
我希望用户能够输入 3 位十进制数字,1.234但step需要这样,0.1它会引发错误并阻止表单提交。
我已经尝试过了step="0.100",但结果是一样的。
我还需要验证其他输入,这样我就无法no validate在<form>标签中使用。
需要做什么?
我会编写一个小的自定义内置自定义元素来执行此操作:
class MyInput extends HTMLInputElement {
constructor(step = 0.1, value = '') {
super();
this.type = 'number';
this.step = this.getAttribute('step') || step;
this.value = this.getAttribute('value') || value;
this.addEventListener('input', (e) => {
this.value = parseFloat(this.value) + 0.034;
})
}
}
customElements.define('my-input', MyInput, { extends: 'input' });
let input = new MyInput(0.1, 1);
document.body.appendChild(input);Run Code Online (Sandbox Code Playgroud)
<!-- if you want to use declaratively: -->
<input is="my-input" step="0.1" value="2" />
<hr />Run Code Online (Sandbox Code Playgroud)
这肯定需要一些调整,例如,如果用户键入输入,但这应该可以作为一个很好的起点。
| 归档时间: |
|
| 查看次数: |
1847 次 |
| 最近记录: |