HTML输入数字,最小+步长,使步长忽略最小值? [英] html input number, min + step, make step ignore min?

查看:68
本文介绍了HTML输入数字,最小+步长,使步长忽略最小值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使 step 步骤忽略 min 属性?

Is it possible to make the step ignore the min attribute?

<input type="number" min="2" step="5"/>

现在,它的步骤如下: 2、7、12、17,...
相反,我希望它是: 2、5、10、15、20,...

As it is now, it steps like so: 2, 7, 12, 17, ...
instead, I'd like it to be: 2, 5, 10, 15, 20, ...

我的真实代码实际上使用动态值,如下所示:

My real code actually uses dynamic values like so:

<input type="number" [min]="someValue" [step]="someStep"/>

一种解决方法可能是创建一条指令,以代替 min step 来执行相同的操作,而无需考虑其他属性.

One way to solve would maybe create a directive to substitute either min or step to do the same thing without taking into consideration the other attribute.

有没有简单的方法可以做到这一点?谢谢!

So is there an easy way to do this? Thank you!

推荐答案

步骤 min max 属性.这是默认的浏览器行为,我认为尝试绕过此行为不是一个好主意.

The step takes the into account the value of the min and max attributes. This is default browser behaviour and I don't think it is a good idea to try and circumvent this.

我将添加一个值为 2 data-min 属性,并将 min 设置为 0 .现在可以检查输入值是否小于自定义最小值,并在需要时更改该值.

I would add a data-min attribute with the value of 2 and set min to 0. Now it is possible to check if the value of the input is less than the custom min value and alter the value when needed.

因为现在最小值为0,这意味着浏览器将遵循您所需的 0 5 10 15

Because now the minimum value is 0 it means that the browser will follow your desired sequence of 0, 5, 10, 15, etc.

const
  inputElement = document.getElementById('input');
  
function onValueChanged(event) {
  const 
    customMin = parseInt(inputElement.getAttribute('data-min'), 10),
    value = parseInt(inputElement.value);
    
  if (value > customMin) {
    return;
  }
  
  inputElement.value = customMin;
}

inputElement.addEventListener('change', onValueChanged);

<input id="input" type="number" min="0" step="5" data-min="2" value="2"/>

这篇关于HTML输入数字,最小+步长,使步长忽略最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆