自动格式化时间js
<html>
<head>
<script language=javascript>
function formatTime(obj)
{
var keytext = String.fromCharCode(event.keyCode);
var otext = obj.value;
if(otext.length == 2 || otext.length == 5)
obj.value = otext + ":";
if(event.keyCode>=48 && event.keyCode<=57 )
{
if(otext.length==1)
{
var val = otext + keytext;
var t = parseInt(val);
if(t>=24)
obj.value = "0" + otext + ":" + keytext;
else
obj.value = otext + keytext + ":";
event.keyCode = 0;
}
else if(otext.length==4)
{
var val = otext.substring(3,4) + keytext;
var t = parseInt(val);
if(t>59)
obj.value = otext.substring(0,3) + "0" + otext.substring(3,4) + ":" + keytext;
else
obj.value = otext + keytext + ":";
event.keyCode = 0;
}
else if(otext.length==7)
{
var val = otext.substring(6,7) + keytext;
var t = parseInt(val);
if(t>59)
obj.value = otext.substring(0,6);
else
obj.value = otext + keytext;
event.keyCode = 0;
}
else if (otext.length==8)
event.keyCode = 0;
}
else
{
event.keyCode = 0;
}
}
</script>
</head>
<body>
<input type=text id="time" onkeypress="formatTime(this)"/><font color=red> 格式 hh:mm:ss</font>
</body>
</html>
<head>
<script language=javascript>
function formatTime(obj)
{
var keytext = String.fromCharCode(event.keyCode);
var otext = obj.value;
if(otext.length == 2 || otext.length == 5)
obj.value = otext + ":";
if(event.keyCode>=48 && event.keyCode<=57 )
{
if(otext.length==1)
{
var val = otext + keytext;
var t = parseInt(val);
if(t>=24)
obj.value = "0" + otext + ":" + keytext;
else
obj.value = otext + keytext + ":";
event.keyCode = 0;
}
else if(otext.length==4)
{
var val = otext.substring(3,4) + keytext;
var t = parseInt(val);
if(t>59)
obj.value = otext.substring(0,3) + "0" + otext.substring(3,4) + ":" + keytext;
else
obj.value = otext + keytext + ":";
event.keyCode = 0;
}
else if(otext.length==7)
{
var val = otext.substring(6,7) + keytext;
var t = parseInt(val);
if(t>59)
obj.value = otext.substring(0,6);
else
obj.value = otext + keytext;
event.keyCode = 0;
}
else if (otext.length==8)
event.keyCode = 0;
}
else
{
event.keyCode = 0;
}
}
</script>
</head>
<body>
<input type=text id="time" onkeypress="formatTime(this)"/><font color=red> 格式 hh:mm:ss</font>
</body>
</html>
测试环境:IE 8