【问题标题】:Mask input for number - percent掩码输入数字 - 百分比
【发布时间】:2017-10-23 15:26:10
【问题描述】:

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

我不使用插件。

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

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

【问题讨论】:

  • 为什么不在输入字段后面加上百分号,省去那部分的麻烦?
  • 如果您知道数字代表百分比,为什么还需要百分号?只需将不带百分号的输入除以 100。
  • 我想用百分号表示用户知道这个数字是一个实数。怎么样?
  • @JimBo,不过,您不需要用户输入百分号。告诉我们更多你想要做什么。发布更多您的网页。
  • 我的意思是在输入字段旁边放一个(永久的,静态的)百分号,而不是痛苦地添加它。

标签: javascript jquery


【解决方案1】:

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

我有点匆忙,所以您可能需要调整样式以使其在跨浏览器中看起来正确。至少它可以让您大致了解。

【讨论】:

  • 在小提琴中有一个 maxlength 属性,但这里没有......所以看看 jsfiddle。
  • 哦,那是非常好。未来的工作是向span 添加一个onclick 处理程序,以关注input,并向input 添加一个纯数字验证。
  • 这就是我要找的
【解决方案2】:

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

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

看看这个fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多