欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

原生js操作input文本框注册获取焦点、失去焦点事件,设置文本框默认值

程序员文章站 2022-06-20 08:39:48
...
<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';
	}
}