获取焦点后隐藏提示内容的输入框

获取焦点后隐藏提示内容的输入框

有趣的小案例池子
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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

极客李华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值