<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>保留小数位数</title>
<script type="text/javascript">
function SaveFloat(sCtrId,nums)
{
if(event.keyCode==8 || event.keyCode==37 || event.keyCode==39)
{
return;
} var s=document.getElementById(sCtrId).value;
if(s==null || s==undefined || s=="") return;
if(nums=="1")
{
if(/[^0-9\.]/.test(s))
return "invalid value";
s=s.replace(/^(\d*)$/,"$1.");
s=(s+"0").replace(/(\d*\.\d)\d*/,"$1");
}
if(nums=="2")
{
if(/[^0-9\.]/.test(s))
return "invalid value";
s=s.replace(/^(\d*)$/,"$1.");
s=(s+"00").replace(/(\d*\.\d\d)\d*/,"$1");
}
if(nums=="3")
{
if(/[^0-9\.]/.test(s))
return "invalid value";
s=s.replace(/^(\d*)$/,"$1.");
s=(s+"000").replace(/(\d*\.\d\d\d)\d*/,"$1"); }
s=s.replace(".",".");
var re=/(\d)(\d{3},)/;
while(re.test(s))
s=s.replace(re,"$1,$2");
s=s.replace(/,(\d\d)$/,".$1");
var ary = s.split('.');
if (ary.length >= 2) {
if (ary[0] == "") {
ary[0] = 0;
}
var temp = ary[1];
if (ary[1].length > nums) {
ary[1] = ary[1].substring(0, nums);
}
document.getElementById(sCtrId).value= ary[0] + "." + ary[1];
return;
}
document.getElementById(sCtrId).value=s.replace(/^\./,"0.");
}
</script>
</head>
<body>
输入数字: <input id="Text1" type="text" onkeyup="SaveFloat(this.id,2)"/>
</body>
</html>
代码奉上,我这个可以及时的保留小数位数,但是每输入一个数字,光标就自动跑到最后面去了,如果里面已经有值了,做了修改每次都自动跑到最后面去,体验效果不好! 有高人赐教下吗?
不要求一定用上面的代码,可以另写,达到要求即可!
希望在firefox ,ie都能用,在IE中优先!
<head>
<title>保留小数位数</title>
<script type="text/javascript">
function FomatFloat(sCtrId,nums,IsBlur){
var s = document.getElementById(sCtrId).value;
if(s==null || s==undefined || s=="") return;
s = s.replace(/([^\d\.])/ig,"");
if(IsBlur){
if(-1==s.indexOf(".")) s+=".";
s += Math.pow(10,nums).toString(10).substring(1);
}
//s = s.replace(/^([\d]*\.[\d]{0,2})(.*)/ig,"$1");
eval("s = s.replace(/^([\\d]*\\.[\\d]{0,"+nums+"})(.*)/ig,\"$1\");");
document.getElementById(sCtrId).value = s.replace(/^\./,"0.");
}
</script>
</head>
<body>
输入数字: <input id="Text1" type="text" onkeyup="FomatFloat(this.id,2,0);" onblur="FomatFloat(this.id,2,1);"/>
</body>
</html>
这个只能在ff中用,IE中根本就达不到效果,我要在IE中用!