<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<center>
<div id="tips"></div>
<div class="box">
<label >用户名:<input id="user" type="text"></label><br /><br />
<label >密   码:<input id="pass" type="password"></label><br /><br />
<button id="login" >登录</button>
</div>
</center>
<script>
window.onload=function(){
addBlur($('user')); // 检测id为user的元素失去焦点后,value值是否为空
addBlur($('pass')); // 检测id为pase的元素失去焦点后,value值是否为空
};
function $(obj){ // 根据id获取指定元素
return document.getElementById(obj);
}
function addBlur(obj){ // 为指定元素添加失去焦点事件
obj.onblur=function(){
isEmpty(this);
};
}
function isEmpty(obj){ // 检测表单是否为空
if(obj.value ===''){
$('tips').style.display ='block';
$('tips').innerHTML='注意:输入内容不能为空!';
}else{
$('tips').style.display='none';
}
}
</script>
</body>
</html>
所用到的知识点:在Wep开发中,焦点事件多用于表单验证功能,是最常用的的事件之一。例如,文本框获取焦点改变文本框的样式,文本框失去焦点时验证文本框内输入的数据等。
focus 当获得焦点时触发(不会冒泡)
blur 当失去焦点时触发(不会冒泡)
编写这个代码,不要看所打的代码不多,但需要思考的地方却很多,当然,当把每一步都理解之后还是能很轻松的把它给写出来。