You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决点击按钮为number类型输入框添加小数点时的值重置问题

数字输入框添加小数点时值被重置的解决办法

我给小数点按钮绑定了点击事件,想实现点击后在输入框末尾添加小数点,但因为输入框类型设为number,执行函数时输入框的值会被直接清空。试过把输入框改成text类型,但这样用户能输入字母,不符合需求。现有代码如下:

JS代码

document.getElementById("decimal").addEventListener("click", () => {
  if (!inputBox.value.includes(".")) {
    inputBox.value += ".";
  }
});

HTML代码

<body>
  <div class="calculator">
    <input type="number" id="inputBox" placeholder="0">
    <div>
      <button class="decimal" id="decimal">.</button>
    </div>
  </div>
  <script src="script.js"></script>
</body>

解决办法

方法一:用text类型配合输入约束(推荐)

把输入框类型改成text,通过inputmode="decimal"让移动端弹出数字键盘,再用pattern限制只能输入数字和小数点,既能满足输入规范,又不会触发number类型的重置问题:

修改后的HTML:

<body>
  <div class="calculator">
    <input type="text" id="inputBox" placeholder="0" inputmode="decimal" pattern="^\d*\.?\d*$">
    <div>
      <button class="decimal" id="decimal">.</button>
    </div>
  </div>
  <script src="script.js"></script>
</body>

JS代码保持原样即可,pattern会限制用户只能输入数字和最多一个小数点,inputmode保证移动端的输入体验和number类型一致。

方法二:保留number类型,优化赋值逻辑

如果一定要用number类型输入框,需要给输入框加上step属性支持小数,同时优化JS里的赋值逻辑,避免自动重置:

修改后的HTML:

<body>
  <div class="calculator">
    <input type="number" id="inputBox" placeholder="0" step="0.01">
    <div>
      <button class="decimal" id="decimal">.</button>
    </div>
  </div>
  <script src="script.js"></script>
</body>

修改后的JS:

document.getElementById("decimal").addEventListener("click", () => {
  const inputBox = document.getElementById("inputBox");
  // 输入框为空时默认设为"0"
  let currentVal = inputBox.value || "0";
  if (!currentVal.includes(".")) {
    currentVal += ".";
    inputBox.value = currentVal;
  }
});

step="0.01"让number输入框允许输入小数,同时手动处理空值情况,确保赋值时不会触发输入框的重置机制。


内容的提问来源于stack exchange,提问作者stilts15

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 11:56:22