数字百分比的掩码输入

Mask input for number - percent

本文关键字:输入 掩码 百分比 数字      更新时间:2023-09-26

如何使用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/

我有点匆忙,所以你可能不得不调整样式,让它看起来正确的跨浏览器。至少它给了你一个大致的概念

我保留了输入数字,移动了百分比字符,然后根据输入的长度(数字的数量)修改了它的位置。

<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">