
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>onblur和onfocus</title>
<style type="text/css">
.red {
border: 1px solid red;
}
</style>
</head>
<body>
姓名:<input type="text" /> <span></span>
<script>
var input = document.querySelector("input");
var span = document.querySelector("span");
input.onfocus = function () {
if (input.value.length === 0) {
span.innerHTML = "请输入用户名";
}
};
input.onblur = function () {
if (input.value.length === 0) {
span.innerHTML = "用户名不能为空";
this.className = "red";
} else {
this.className = "";
span.innerHTML = "";
}
};
</script>
</body>
</html>