当文本框里有placeholder属性时,获得焦点,没有清空文本框
<input type="text" placeholder="请输入搜索关键字" id="txtSearch">
<input type="button" value="搜索" id="btnSearch">
效果如图:
想要文本框获取焦点时清空文本框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>搜索文本框</title>
<style>
.gray {
color: gray;
}
.balck {
color: black;
}
</style>
</head>
<body>
<input type="text" class="gray" value="请输入搜索关键字" id="txtSearch">
<input type="button" value="搜索" id="btnSearch">
<script>
//当文本框获得焦点,如果文本框里的内容是 请输入搜索关键字 则清空文本框,并且让字体变成黑色
var txtSearch = document.getElementById("txtSearch");
//获取焦点的事件
txtSearch.onfocus = function() {
if (this.value == "请输入搜索关键字") {
this.value = "";
this.className = "black";
}
}
//当文本框失去焦点,如果文本框里的内容为空 还原文本框里的文字,并且让文字变成灰色
//失去焦点事件
txtSearch.onblur = function() {
//判断文本框中的内容为空
//if (this.value == "")
if (this.value.length == 0) {
this.value = "请输入搜索关键字";
this.className = "gray";
}
}
</script>
</body>
</html>