如何在输入中设置起始值并在键盘输入时替换该值?

时间:2019-06-09 10:39:56

标签: javascript html angular typescript

  1. 如何在输入中使起始值0.00?
  2. 以及如何在键盘输入时替换此值? (如果通过键盘输入类型1:0.01、0.11、1.11)

h1 {
  font-size: 20px;
}

input {
  height: 45px;
  width: 300px;
  font-size: 30px;
  direction: rtl;
}
<h1>starting value 0.00</h1>
<h1>if type 1 from keyboard update value as 0.01</h1>
<h1>if type next 1 from keyboard update value as 0.11</h1>
<h1>if type next 1 from keyboard update value as 1.11</h1>
<input type="text">

2 个答案:

答案 0 :(得分:0)

在输入元素的标记中的html中

具有以下内容:oninput="this.value = this.value.toFixed(2)"

所以这看起来像是您的标记:

<input
oninput="this.value = this.value.toFixed(2)"
/>

现在toFixed()还将事物转换为字符串,因此它可能不是您要尝试的事情,似乎加上了这两个小数位以及如何做到最好使其在所有浏览器中兼容并一致仍然有争议,这些stackoverflow线程充满了选择: Round to at most 2 decimal places (only if necessary) JavaScript math, round to two decimal places [duplicate]

答案 1 :(得分:0)

document.querySelector('input').addEventListener('keypress', function(e) {
  e.preventDefault();

  const
    oldVal = this.value,
    newVal = oldVal.replace(/(0)(?!.*\1)/, e.key);

  this.value = newVal === oldVal ? `${e.key}${oldVal}` : newVal;
});
h1 {
  font-size: 20px;
}

input {
  height: 45px;
  width: 300px;
  font-size: 30px;
  direction: rtl;
}
<h1>starting value 0.00</h1>
<h1>if type 1 from keyboard update value as 0.01</h1>
<h1>if type next 1 from keyboard update value as 0.11</h1>
<h1>if type next 1 from keyboard update value as 1.11</h1>
<input type="text" value="0.00">