我在 HTML 中有这段代码:
<input type="number" step="0.1" class="form-group">
我希望用户能够输入 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);
<!-- if you want to use declaratively: -->
<input is="my-input" step="0.1" value="2" />
<hr />
这肯定需要一些调整,例如如果用户在输入中键入内容,但这应该可以很好地作为起点。
关于javascript - HTML input type=number 步骤阻止表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56786140/