Js实现简单的搜索框(获取焦点、失去焦点)
笔记
onfocus
onblur
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>模拟搜索框</title>
<style>
input {
color: gray;
}
</style>
</head>
<body>
<input type="text" value="请输入要搜索的内容" id="txt">
<script src="common.js"></script>
<script>
// 获取文本框
// 注册获取焦点的事件
my$("txt").onfocus = function() {
// 判断文本框的内容是不是默认的内容
if (this.value == "请输入要搜索的内容") {
this.value = "";
this.style.color = "black";
}
}
// 注册失去焦点的事件
my$("txt").onblur = function() {
// 判断文本框的内容是否为空
// this.value == "" (字符串比较方式比length慢)
if (this.value.length == 0) {
this.value = "请输入要搜索的内容";
this.style.color = "gray";
}
}
</script>
</body>
</html>
common.js
function my$(id) {
return document.getElementById(id);
}