设置输入类型=数字的步骤

时间:2018-03-01 11:17:04

标签: javascript html

以下html标记显示一个输入字段,该字段接受一个数字,并提供向上,向下箭头以递增,递减字段值。 我所需的输入字段是输入,其中板球的值超过,例如,如果我点击向上箭头,它应该转换为2或2.0而不是1.6

<input type="number" name="overs" step="0.1">

我知道在单击向上和向下箭头时需要执行一些javascript,但我不知道该怎么做。任何人都可以建议如何处理这个箭头点击事件。此外,该字段接受手动输入的数值,同样需要验证以限制板球的无效值,例如:1.8无效。 请指导。

3 个答案:

答案 0 :(得分:1)

添加事件监听器input)并增加整数值,分数值大于或等于{{1} }

0.6

<强>演示

&#13;
&#13;
input.addEventListener( "input", function(){
   var value = this.value;
   if ( value - parseInt( value ) >= 0.6 )
   {
      this.value = Math.ceil( value );
   }
})
&#13;
var input = document.querySelector( "[name='overs']" );

input.addEventListener( "input", function(){
   var value = this.value;
   if ( value - parseInt( value ) >= 0.6 )
   {
      this.value = Math.ceil( value );
   }
})
&#13;
&#13;
&#13;

为减少过度,请同时收听<input type="number" name="overs" step="0.1">

注意

  • 下面的演示使用向下箭头键,而不是箭头单击。

<强>演示

&#13;
&#13;
keyup
&#13;
var input = document.querySelector( "[name='overs']" );

input.addEventListener( "input", function(){
   var value = this.value;
   if ( value - parseInt( value ) >= 0.6 )
   {
      this.value = Math.ceil( value );
   }
});

input.addEventListener( "keyup", function(){
    var value = this.value;
    var step = +this.getAttribute( "step" );
    console.log(event.which);
   if ( event.which == 40 )
   {
      event.preventDefault();
      value = value - step;
      if ( (value - parseInt( value )) >= 0.5 )
      {
         this.value = parseInt( value ) + 0.5;
      }
   }
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试此链接代码

https://www.w3schools.com/html/tryit.asp?filename=tryhtml_input_number

CREATE CAST (source_type AS target_type)
    WITH FUNCTION function_name (argument_type [, ...])
    [ AS ASSIGNMENT | AS IMPLICIT ]

CREATE CAST (source_type AS target_type)
    WITHOUT FUNCTION
    [ AS ASSIGNMENT | AS IMPLICIT ]

CREATE CAST (source_type AS target_type)
    WITH INOUT
    [ AS ASSIGNMENT | AS IMPLICIT ]

答案 2 :(得分:0)

您可以检查分数是否> 0.5并围绕它:

&#13;
&#13;
document.querySelector('.input-round-up').addEventListener('input', function (e) {
  var value = e.target.value;
  var isDecrementing = value < this.__lastValue;
  if ((value % 1) > 0.5 && !isDecrementing) {
    e.target.value = Math.round(value);
  }
  this.__lastValue = value;
});
&#13;
<input class="input-round-up" type="number" name="overs" step="0.1" />
&#13;
&#13;
&#13;