日期:2014-05-17  浏览次数:20662 次

js和html模拟系统的ip地址输入框
<script>
//e为 event o为input对象 i 为 第几个输入框
function ipVali(e,o,i)  //48-57 96-105  223 255  key Code== 8 退格键
{	//alert(e.keyCode)
	// 96-105 小键盘数字键 48-57大键盘数字键 8 退格键  46 del键  16 shift键    116 刷新   190 大键盘的点   110小键盘的点  9 tab
	var inputs = o.parentNode.getElementsByTagName("input");
	if(e.keyCode == 9 || (e.keyCode >= 96 && e.keyCode <= 105) ||(e.keyCode >= 48 && e.keyCode <= 57) || e.keyCode==8 || e.keyCode==46|| e.keyCode==116 || e.keyCode == 16)
	{
	    if(e.shiftKey && e.keyCode >= 48 && e.keyCode <= 57)
        {
            if(e.keyCode != 56)
            return false;
        }
		if(e.keyCode == 8 || e.keyCode == 9)
		{
			return true;
		}
		
		
		if(o.value.length >= 3 && getRangeByObj(o) == '')
		{
			if(null != inputs[i+1])
			{
				inputs[i+1].focus();
			}
			
		}
	}
	else if(190 == e.keyCode || 110 == e.keyCode)  //输入的是点
	{ 
		if(o.value == '')
		{
			for(var j=0; j<=i; j++)
			{	
				//alert(inputs[j].value);
				if(inputs[j].value == '')
				{
					inputs[j].value="*";
				}
			}
		}
		inputs[i+1].focus();
		return false;
	}
	else
	{
		return false;
	}
}

function ipVali2(o,i)
{
	if(o.value != '')
	{
		if(i == 1) //ip地址的第一个字段
		{
			if(o.value > 223)
			{
				o.value = 223;
			}
		}
		else 
		{
			if(o.value > 255)
			{
				o.value = 255;
			}
		}
	}
	else 
	{
		o.value = "*";
	}
}

function getRangeByObj(obj) 
{ 
	var word=''; 
	if (document.selection){
		o=document.selection.createRange();
		if(o.text.length>0)word=o.text;
	}else{ 
		p1=obj.selectionStart;
		p2=obj.selectionEnd; 
		if (p1||p1=='0'){
			if(p1!=p2)word=obj.value.substring(p1,p2);
		}
	} 
	
	return word; 
} 
</script>


<span class="ipInput">
	<input onkeydown="return ipVali(event,this,0);" onblur="return ipVali2(this,1);" type="text" maxlength="3" size="3"/>.
	<input onkeydown="return ipVali(event,this,1);" onblur="return ipVali2(this,2);" type="text" maxlength="3" size="3"/>.
	<input onkeydown="return ipVali(event,this,2);" onblur="return ipVali2(this,2);" type="text" maxlength="3" size="3"/>.
	<input onkeydown="return ipVali(event,this,3);" onblur="return ipVali2(this,2);" type="text" maxlength="3" size="3"/>
</span>