本文主要包含number,字体随长度变化,小数位等相关知识,张营希望在学习及工作中可以帮助到您
需求:
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>