代码之家  ›  专栏  ›  技术社区  ›  vanowm

用大于'number.MAX\u SAFE\u INTEGER'(9007199254740992)的数字模拟输入type=“number”?

  •  1
  • vanowm  · 技术社区  · 3 年前

    我在努力模仿 <input type="text"> <input type="number"> (上/下箭头键增大/减小值)

    Number.MAX_SAFE_INTEGER (9007199254740992)停止增加,但 type="number" 可以超过这个数字。 有没有办法绕过javascript的这个限制?

    const input = document.querySelector('input[type="text"]'),
          step = {ArrowUp: 1, ArrowDown: -1};
    
    input.addEventListener("keydown", (e) =>
    {
      if (step[e.key])
      {
        input.value = Number(input.value) + step[e.key];
        return e.preventDefault();
      }
    });
    <table>
      <tr>
        <td>type="text"</td>
        <td><input type="text" value="9007199254740990"></td>
        <td>use UP/DOWN arrow keys</td>
      </tr>
      <tr>
        <td>type="number"</td>
        <td><input type="number" value="9007199254740990"></td>
      </tr>
    </table>
    1 回复  |  直到 3 年前
        1
  •  1
  •   CertainPerformance    3 年前

    简单地使用BigInt表示法似乎可以达到以下目的:

    const input = document.querySelector('input[type="text"]'),
          step = {ArrowUp: 1n, ArrowDown: -1n};
    
    input.addEventListener("keydown", (e) =>
    {
      if (step[e.key])
      {
        input.value = BigInt(input.value) + step[e.key];
        return e.preventDefault();
      }
    });
    <table>
      <tr>
        <td>type="text"</td>
        <td><input type="text" value="9007199254740990"></td>
        <td>use UP/DOWN arrow keys</td>
      </tr>
      <tr>
        <td>type="number"</td>
        <td><input type="number" value="9007199254740990"></td>
      </tr>
    </table>

    如果您担心过时的浏览器,可以使用 alternative implementation 复制BigInt。