设置搜索文本框的样式
如下图所示为搜索文本框的默认样式,当文本框获得焦点时,清空文本框,并且让输入字体变为黑色;当文本框失去焦点时,如果文本框里的内容为空,则还原文本框里的文字,并且让字体颜色变为灰色
完成以上要求,我新掌握了2个事件:
- onblur 事件会在对象失去焦点时发生
- onfocus 事件在对象获得焦点时发生
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.gray {
color: gray;
}
.black {
color: black;
}
</style>
</head>
<body>
<input type="text" class="gray" value = "请输入搜索关键字" id= "txtSearch">
<input type="button" value="搜索" id = "btnSearch">
<script type="text/javascript">
//当文本框获得焦点, 清空文本框,并且让字体变为黑色
//当文本框失去焦点 如果文本框内容为空 还原文本框的文字,并且让字体变为灰色
var txtSearch = document.getElementById('txtSearch');
//获取焦点的事件 focus
txtSearch.onfocus = function () {
this.value = '';
this.className= "black"
}
//当文本框失去焦点时,如果文本框里的内容为空 还原文本框里的文字,并且让字体颜色变为灰色
txtSearch.onblur = function () {
var y = this.value.length
if (y === 0){
this.value = '请输入搜索关键字';
this.className = 'gray';
}
}
</script>
</body>
</html>