简体   繁体   English

这是使用值替换更新输入类型=数字字段的预期行为

[英]Which is the intended behaviour on update of input type=number field with value replace

During writing on a calculator with Javascript I ran into different behavior of <input type=number> fields in Chrome and Firefox. 在使用Javascript编写计算器的过程中,我遇到了Chrome和Firefox中<input type=number>字段的不同行为。

If for whatever reason, you replace the value of the input field you're typing in with its own value inside an event listener attached to the input field, it is impossible to write numbers with decimals into the field in Firefox: 如果出于某种原因,将输入的输入字段的值替换为输入字段附带的事件侦听器中的值,则无法在Firefox中将带小数的数字写入该字段:

 window.addEventListener("input", function(e){ if(document.getElementById("activator").checked){ e.target.value = e.target.value; } }); 
 <input type="number" step="0.00001"> <label> <input type="checkbox" id="activator"> Activate JS value override </label> 

I wonder if this behavior in Firefox is intended or maybe even the standard? 我想知道Firefox中的这种行为是故意的还是什至是标准的? Or is there no standard defined and it's up to the browser's engine to define what happens with the value or how the value is processed? 还是没有定义标准,由浏览器的引擎来定义值会发生什么或如何处理值?

Edit: I checked the behavior in Edge and it behaves like Chrome. 编辑:我检查了Edge中的行为,其行为类似于Chrome。 Also, I only checked it with German locale (except Edge which seems to ignore the locale) in Chrome and FF, but it probably is still the same with dots as decimal separators. 另外,我仅在Chrome和FF中使用德语语言环境(“ Edge”(它似乎忽略了语言环境))检查了它,但点与小数点分隔符可能仍然相同。

Edit2: Updated the fiddle to show that the issue does not derive from the "step"-attribute. Edit2:更新了小提琴,以表明该问题并非源于“步骤”属性。

Imagine you enter 3.5 . 假设您输入3.5

The reason will be that the moment you enter the decimal separator . 原因是您输入小数点分隔符的那一刻. will also trigger your listener, which will attempt so set an illegal value "3." 也会触发您的侦听器,这将尝试将其设置为非法值"3." . Somehow Chrome seems to have a workaround for that issue, setting the invalid value manually doesn't work in Chrome either: Chrome似乎可以解决该问题,手动设置无效值在Chrome中也不起作用:

 window.addEventListener("input", function(e) { if (document.getElementById("activator").checked) { e.target.value = e.target.value; } }) foo.addEventListener('click', () => { numberinput.value = "3."; }) 
 <input type="number" step="0.00001" id="numberinput"> <label> <input type="checkbox" id="activator"> Activate JS value override </label> <button type="button" id="foo">Set 3. as value</button> 

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

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