这里需要使用宽度相同的字体,比如数字1和数字8是等宽的,这里使用的是dinpro-regular.otf
需求:
1.允许输入15位整数,两位小数
2.输入框宽度固定,字体随内容的长度变化
3.禁止输入多个0开头
ps: 以上前提是用户输入的是数字,非数字报错处理(判断是否为空)
<!doctype html><html lang="en"><head>
<meta charset="utf-8">
<title>document</title>
<style type="text/css">
*{margin:0;padding:0;}
@font-face{
font-family: "dinpro";
src: url("font/dinpro-regular.otf");
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button{
-webkit-appearance: none !important;
}
#aa{
width: 300px;
height: 50px;
font-size: 40px;
font-family: "dinpro";
}
</style>
</head>
<body>
<input type="number" id="aa">
<script type="text/javascript" src="jquery-1.11.3.min.js">
</script><script type="text/javascript">
$("#aa").on("input",function(){
var value = $(this).val();
if(value.indexof(".")==-1){//没有小数点
//禁止输入多个0开头 输入00变为0 输入01后变为1
if( (parsefloat(value)==0 && value.length>1) || (parsefloat(value)!=0 && value.charat(0)=="0") ){
$(this).val(value.substring(1));
}
if(value.length>15){
$(this).val(value.slice(0,15));
}
}else{//有小数点
//取两位小数
$(this).val(math.floor(value*100)/100);
} //控制字体大小 14是输入框刚好可以显示的数字位数,具体根数实际情况设置
if($(this).val().length>14){
$(this).css("font-size",40*(14/$(this).val().length)+"px");
}else{
$(this).css("font-size","40px");
}
});
</script>
</body>
</html>
以上就是用number输入框限制输入数字位数、字体随数字长度变化方法的详细内容。