javascript 数字的掩码输入 - 百分比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7933505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:47:32  来源:igfitidea点击:

Mask input for number - percent

javascriptjquery

提问by JimBo

How can create a mask input for number that have percent by jQuery? Do I make input just accept until three numbers and put percent sign after numbers while user finished typing(keyup)?

如何通过jQuery为具有百分比的数字创建掩码输入?我是否让输入只接受直到三个数字并在用户完成输入(keyup)时在数字后面加上百分号?

I don't use plugins.

我不使用插件。

Example: 1%Or 30%Or 99%Or 100%Or 200%

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

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

回答by Andy E

You're better off not using JavaScript for this. Besides the problems that come with using onkeyupfor detecting text input, you also have the hassle of parsing the resulting string back to a number in your client/server scripts. If you want the percent sign to look integrated, you could do something like this:

最好不要为此使用 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/

http://jsfiddle.net/BvVq4/

I'm rushing slightly, so you may have to tweak the styles to get it to look right cross-browser. At least it gives you the general idea.

我有点匆忙,所以您可能需要调整样式以使其在跨浏览器中看起来正确。至少它给了你一般的想法。

回答by Roysh

I've stayed with input number, moved the percentage char and then modified its position according to the length of the input (the amount of digits).

我一直使用输入数字,移动百分比字符,然后根据输入的长度(位数)修改其位置。

HTML

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

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

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');
   }
});

Check out this fiddle

看看这个小提琴