繁体   English   中英

如何在输入中创建起始值并在键盘输入时替换此值?

[英]How to make starting value in input and replacing this value while keyboard input?

  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"> 

在输入元素的标记中的html中,有这样的: oninput="this.value = this.value.toFixed(2)"

所以这看起来像你的标记:

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

现在toFixed()将事物转换为字符串,所以它可能不是你想要做的事情,似乎添加这两个小数位以及如何最好地兼容所有浏览器并保持一致仍然是为了辩论,这些stackoverflow线程充满了选项: 舍入到 最多2个小数位(仅在必要时) JavaScript数学,舍入到两个小数位[重复]

 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"> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM