• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ellaha
博客园    首页    新随笔    联系   管理    订阅  订阅
JS事件之获取、失去文本框焦点

JS事件:https://www.w3school.com.cn/jsref/jsref_events.asp

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .gray {
            color: #808080;
        }
        .black {
            color: #000;
        }
    </style>
    <script>
        window.onload = function () {
            //当文本框获得焦点 如果文本框内容为请输入关键字 清空文本框内容 并让字体呈黑色
            var txtSearch = document.getElementById('txtSearch');
            // 在事件处理函数中,this代表触发该函数的对象
            txtSearch.onfocus = function () {
                if (this.value === '请输入关键字') {
                    this.value = '';
                    this.className = 'black';
                }
            }
            // 当文本框失去焦点 如果文本框内容为空 还原文本框内容 字体呈灰色
            txtSearch.onblur = function () {
                if (this.value.length === 0 || this.value === '请输入关键字') {
                    this.value = '请输入关键字';
                    this.className = 'gary';
                }
            }
        }
    </script>
</head>
<body>
<input type="text" name="" id="txtSearch" value="请输入关键字" class="gray">
<input type="button" value="搜索">
</body>
</html>

 

posted on 2021-03-16 08:05  ellaha  阅读(752)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3