簡體   English   中英

數字的掩碼輸入 - 百分比

[英]Mask input for number - percent

如何為百分比為 jQuery 的數字創建掩碼輸入? 當用戶完成輸入( keyup )時,我是否只接受輸入直到三個數字並在數字后面加上百分號?

我不使用插件。

示例: 1%30%99%100%200%

<input name="number" class="num_percent">

你最好不要使用JavaScript。 除了使用onkeyup檢測文本輸入時出現的問題,您還可以將生成的字符串解析回客戶端/服務器腳本中的數字。 如果您希望百分號看起來是集成的,您可以執行以下操作:

<div class="percentInput">
    <input type="text" name="number" class="num_percent">
    <span>%</span>
</div>
.percentInput { position:relative; }
.percentInput span { position: absolute; right: 4px; top:2px; }
.num_percent { text-align: right; padding-right: 12px; }

http://jsfiddle.net/BvVq4/

我很急,所以你可能需要調整樣式才能讓它看起來正確的跨瀏覽器。 至少它給你一般的想法。

我一直使用輸入數字,移動百分比字符然后根據輸入的長度(數字位數)修改其位置。

HTML

<input type="number" min="0" max="100" value="100"> //chose 100 only for the sake of the example
<span class="percentage-char">%</span> 

CSS

input {
  width: 55px;
  height: 20px;
  font-size:18px;
}
.percentage-char {
  position: absolute;
  left: 32px; // default position - in this case 100
  top: 1px;
  font-size: 18px; 
}
.one-digit { //position of the '%' when input is 0-9
  left: 13px;
}
.two-digits{ //position of the '%' when input is 10-99
  left: 24px;
}

JS

$(":input").change(function() { //listening to changes on input
   if ($(this).val() < 10) { //adding and removing the classes
        $('.percentage-char').removeClass('two-digits');
        $('.percentage-char').addClass('one-digit');
   } else if ($(this).val() > 9 && $(this).val() < 100) {
        $('.percentage-char').addClass('two-digits');
   } else {
        $('.percentage-char').removeClass('one-digit two-digits');
   }
});

看看這個小提琴

 function setPercentageMask() { let input = $('.percent'); input.mask('##0,00', {reverse: true}); input.bind("change keyup", function() { isBetweenPercentage($(this)); }); } function isBetweenPercentage(input) { let myNumber = (input.val())? parseFloat(input.val()): 0; (myNumber.isBetween(0, 100.00))? myNumber: input.val('100,00'); } if (typeof(Number.prototype.isBetween) === "undefined") { Number.prototype.isBetween = function(min, max, notBoundaries) { var between = false; if (notBoundaries) { if ((this < max) && (this > min)) between = true; } else { if ((this <= max) && (this >= min)) between = true; } return between; } } setPercentageMask();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <input name="text" class="percent">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM