[英]How to customize the step of a number input field?
我有一個number
類型的輸入字段,范圍從1
到4096
,如下所示:
<input max="4096" min="1" name="size" step="2" type="number" value="4096">
我目前使用step = 2
,結果是數字2, 4, 6, 8, 10, ...
1 , 2, 4, 8, 16,...
加倍?注意:
該字段只能包含這些值(用戶不應插入3 , 5 , 6, 7, ...
)。 它應該適用於增量和減量。
我會使用javascript在變化時動態改變你的步驟
<input max="4096" min="1" name="size" step="2" type="number" value="4096" id="foo">
<script type="text/javascript">
$('#foo').change(function(){
this.step=this.value;
});
</script>
本機步進器不符合您的要求。 您最好的選擇是實施自定義解決方案。
我舉了一個例子。 看看它:
$('.steps').text($('.steps').data('min')); $('.step').click(function() { if ($('.steps').text() == 1 && $(this).hasClass('down') || +$('.steps').data("max") == +$('.steps').text() && $(this).hasClass('up')) return; if ($(this).hasClass('up')) $('.steps').text($('.steps').text() * 2); else $('.steps').text($('.steps').text() / 2); });
.stepper { width: 75px; height: 30px; border: 1px solid #C0C0C0; display: inline-block; } .steps { width: 55px; float: left; display: inline-block; text-align: center; line-height: 30px; } .step { font-size: 8px; width: 20px; padding: 0px; float: right; } .step.up { vertical-align: top; } .step.down { vertical-align: bottom; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="stepper"> <span class="steps" data-min="1" data-max="4096"></span> <button type="button" class="step up">▲</button> <button type="button" class="step down">▼</button> </div>
這有效。
$("#numbercruncher").change(function(){ var a=parseInt($("#numbercruncher").val()); var b =a*2-1; $("#numbercruncher").attr("step",b); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="number" min="1" max="1000" id="numbercruncher"step="2">
或這個
<input type="number" min="1" max="2000" onchange="this.step=this.value*2-1">
這個線程很舊,但現在,只需在 html 標簽中輸入 step:
<!DOCTYPE html>
<html>
<body>
<h1>The input step attribute</h1>
<form action="/action_page.php">
<label for="points">Points:</label>
<input type="number" id="points" name="points" step="0.2">
<input type="submit">
</form>
</body>
</html>
資料來源: W3CSchool
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.