<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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 () {
if (this.value.length == 0) {
this.value = "请输入搜索内容";
this.style.color = "gray";
}
};
</script>
</body>
</html>
common.js
/**
* 根据id属性的值,返回对应的标签元素
* @param id id属性的值,string类型的
* @returns {Element} 元素对象
*/
function my$(id) {
return document.getElementById(id);
}