获取焦点后隐藏提示内容的输入框
有趣的小案例池子:
JS实现定时器
JS实现关闭图片窗口
JS实现输入检验
获取焦点后隐藏提示内容的输入框
JS实现获取鼠标在画布中的位置
聊天信息框显示消息
JS点击切换背景图
自动切换背景的登录页面
JS制作跟随鼠标移动的图片
JS实现记住用户密码
效果展示
概述
本文讲解如何制作,当获取文本框内容焦点后,然后隐藏文本框中提示内容的输入框。
构建HTML框架
<body>
<input type="text" value="内容">
</body>
CSS样式
<style>
input {
/* 设置输入框中的内容 */
color: #999;
}
</style>
JS逻辑
<script>
// 获取元素
var text = document.querySelector('input');
// 注册事件 获得焦点事件 onfocus
text.onfocus = function() {
if (this.value === '内容') { // 当获取到内容的时候
this.value = ''; // 我们将框中的内容设置为空
}
// 然后把输入文字的样式设置为黑色
this.style.color = '#333';
}
// 注册事件 失去焦点事件 onblur
text.onblur = function() {
if (this.value === '') {
this.value = '内容';
}
// 失去焦点之后把颜色变化回去
this.style.color = '#999';
}
</script>
完整代码
<!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>Document</title>
<style>
input {
color: #999;
}
</style>
</head>
<body>
<input type="text" value="内容">
<script>
// 获取元素
var text = document.querySelector('input');
// 注册事件 获得焦点事件 onfocus
text.onfocus = function() {
if (this.value === '内容') { // 当获取到内容的时候
this.value = ''; // 我们将框中的内容设置为空
}
// 然后把输入文字的样式设置为黑色
this.style.color = '#333';
}
// 注册事件 失去焦点事件 onblur
text.onblur = function() {
if (this.value === '') {
this.value = '内容';
}
// 失去焦点之后把颜色变化回去
this.style.color = '#999';
}
</script>
</body>
</html>