[英]Making the step act as a guide in <input type=“number”>
How could I make the step attribute for a <input type="number">
act more of a guide, so I could input any positive integer but the increment arrows would change the current value by a fixed amount. 我怎样才能使
<input type="number">
的step属性发挥更多的指导作用,所以我可以输入任何正整数,但是增量箭头会将当前值更改为固定值。
eg I could enter 0,1,2,3,4,5,6,7,... and the step would increment the values as 0,6,12,18,24,... etc... 例如,我可以输入0,1,2,3,4,5,6,7,...,该步骤会将值递增为0,6,12,18,24,...等。
I could implement this if I knew how to capture the step up/step down events in javascript. 如果我知道如何捕获javascript中的升/降事件,则可以实现此功能。 However, I can't find a way to do that.
但是,我找不到办法。 I've shown exactly what I'd like in the pseudo code below:
我已经在下面的伪代码中确切显示了我想要的:
<input id="num" type="number">
<script>
inp = document.getElementById("num");
var increment = 6;
if ( step up pressed ){
inp.value += increment;
}
else if (step down pressed ){
inp.value -= increment;
}
</script>
这行得通吗?
<input id="num" type="number" step="6">
It seems like a horrible hack but here's an answer to my question: 看来这是一个可怕的骇客,但这是我的问题的答案:
<input id='num' type=number step=0.00001 onchange="increment()">
<script>
document.prev_num = document.getElementById("num").value;
function increment() {
var step = 6;
var catch_step = 0.00001;
var curr_num = parseFloat(document.getElementById("num").value);
if ( Math.abs(curr_num - (document.prev_num + catch_step)) < 1e-7 ){
curr_num = curr_num - catch_step + step;
}
else if (Math.abs(curr_num - (document.prev_num - catch_step)) < 1e-7){
curr_num = curr_num + catch_step - step;
}
else if (curr_num != parseInt(curr_num)){
alert("You can only input integers.")
curr_num = parseInt(curr_num);
}
document.getElementById("num").value = curr_num;
document.prev_num = curr_num;
}
</script>
So HTML forces the numbers to be multiples of 0.00001, which includes all integers. 因此,HTML强制数字为0.00001的倍数,其中包括所有整数。
Javascript then acts when the number is changed. 然后,当数字更改时,Javascript起作用。 If that change is only a change of 0.000001 the step button was almost certainly pressed.
如果该更改仅更改为0.000001,则几乎可以肯定已按下了步骤按钮。
Non integers won't be accepted. 非整数将不被接受。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.