<input type="text" value="请输入关键字" class="gray" id="txtInput">
// 文本框中有灰色字体的“请输入关键字”提示,获取焦点时,清空文本框,输入的字体显示为黑色,当文本框为空失去焦点时,显示默认提示文字
// 1. 获取元素
var txtInput = document.getElementById('txtInput');
// 2. 注册获取焦点事件
txtInput.onfocus = function () {
if (txtInput.value === '请输入关键字') {
this.value = '';
this.className = 'black';
}
}
// 3. 注册失去焦点事件
txtInput.onblur = function () {
// if (txtInput.value === '') {
// if (txtInput.value.length === 0 判断字符串的值是否为空时常用
if (txtInput.value.length === 0 || txtInput.value === '请输入关键字') {
this.value = '请输入关键字';
this.className = 'gray';
}
}