掩码输入数量 – 百分比

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

我不使用插件。

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

  

你最好不要使用JavaScript。 除了使用onkeyup检测文本输入时出现的问题,您还可以将生成的字符串解析回客户端/服务器脚本中的数字。 如果您希望百分号看起来是集成的,您可以执行以下操作:

 
%
 .percentInput { position:relative; } .percentInput span { position: absolute; right: 4px; top:2px; } .num_percent { text-align: right; padding-right: 12px; } 

http://jsfiddle.net/BvVq4/

我很急,所以你可能需要调整样式才能让它看起来正确的跨浏览器。 至少它给你一般的想法。

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

HTML

  //chose 100 only for the sake of the example % 

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

看看这个小提琴