html - <input type ="number"/> with a custom step "n"but allow decimals

标签 html input numbers decimal

我想要一个 <input type="number">有一个没有小数的步骤,但继续允许输入小数,所以该字段不会进入无效状态

<input type="number" step="5.00000" />

^ 将增加 5,但将 5.5 放入该字段将导致无效状态。

更好地理解这里:https://stackblitz.com/edit/angular-89ydzs

最佳答案

解决方法如下:

<input type="number" step="any" />

此外,您还可以使用 javascript 输入您自己的数字。

function inRangeOf(value, min, max) {
  if (min !== undefined) value = Math.max(min, value);
  if (max !== undefined) value = Math.min(max, value);
  return value;
}

function processValue(value, min, max) {
  var dots = value.match(/\./g);
  if (value.length > 1 && value[value.length - 1] == '.' && value[value.length - 2] != '-' && (!dots || dots.length < 2)) {
    return inRangeOf(parseFloat(value.substring(0, value.length-1)), min, max) + '.';
  } else {
    return inRangeOf(parseFloat(value), min, max);
  }
}

function processKey(evt, min, max) {
  if (evt.key == 'ArrowUp') {
    evt.target.value = inRangeOf((parseFloat(evt.target.value) || 0) + 1, min, max) + '';
    return true;
  } else if (evt.key == 'ArrowDown') {
    evt.target.value = inRangeOf((parseFloat(evt.target.value) || 0) - 1, min, max) + '';
    return true;
  }
}
<input type="text" oninput="this.value = processValue(this.value, 0, 100) || ''" onkeydown="return processKey(event, 0, 100)" />

关于html - &lt;input type ="number"/> with a custom step "n"but allow decimals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57390313/

相关文章:

html - 使用 border-radius 绘制理想的对称 css 边框

c - 如何测试数字是否存在科学记数法?

c++ - 我认为随机数生成器在不应该被调用的时候被调用

linux - 在 linux 中使用 sed 替换字符串后面的数字时得到一个额外的数字

input - Ii 如何在我的组件中获得 ionic 2 中的输入值?

html - 自动填充在与自动填充无关的 chrome 输入中弹出

jquery - 页面刷新时表单数据消失

html - sIFR3 平滑和 IE

html - 选择最后一个嵌套元素

css - W3CSS : centering input field