2011-10-28 55 views
2

如何创建一个掩码输入的数量有百分比的jQuery?我是否只需要输入三个数字,然后在用户输入完毕后在数字后面加百分号(keyup)?掩码输入的数量 - 百分比

我不使用插件。

例: 1%或者30%或者99%或者100%或者200%

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

为什么不把百分号放在输入字段后面并保存那部分麻烦? –

+0

你的建议是什么? – JimBo

+0

如果您知道数字代表百分比,您为什么需要百分号?只需输入没有百分号的数字并除以100即可。 –

回答

9

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

我略冲,所以你可能需要调整的样式来获得它看起来是正确的跨浏览器。至少它给你的一般想法。

+1

在小提琴中有一个maxlength属性,但不在这里...所以看看jsfiddle。 –

+2

哦,这是非常好的。未来的工作是在'span'上添加一个'onclick'处理程序,该''span''关注'input',并为'input'添加一个仅用于数字的验证。 –

0

我住在输入号码,移动百分比字符,然后根据输入的长度(数字的数量)修改其位置。

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