js input获取焦点和失去焦点的操作

本文介绍了一种使用JavaScript实现的文本框颜色动态调整方法。当文本框获得焦点时,其背景和文字颜色会发生预设变化;而当文本框失去焦点时,其背景和文字颜色将随机变化。通过简单的代码示例,展示了如何利用onfocus和onblur事件来实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

获得焦点时改变文本框的背景和文字颜色,失去焦点时文本框的背景和文字颜色随机改变

onfocus获取焦点
onblur 失去焦点

<input type="text" value="根据焦点操作">
<style>
        input {
            width: 400px;
            height: 40px;
            line-height: 40px;
            border: 1px solid #ddd;
            border-radius: 6px;
            display: block;
            margin: 40px auto;
            padding: 0 10px;
            outline: none
        }
    </style>
window.onload = function () {
            var inputs = document.querySelector("input");
            inputs.onfocus = function () {
                this.style.backgroundColor = "#ccc";
                this.style.color = "#666";
            };
            inputs.onblur = function () {
                //Math.random()生成随机数
                //Math.floor()取整
                var r = Math.floor(Math.random() * 256);
                var g = Math.floor(Math.random() * 256);
                var b = Math.floor(Math.random() * 256);

                var r1 = Math.floor(Math.random() * 256);
                var g1 = Math.floor(Math.random() * 256);
                var b1 = Math.floor(Math.random() * 256);
                this.style.backgroundColor = 'rgb(' + r + ',' + g + ',' + b + ')';
                this.style.color = 'rgb(' + r1 + ',' + g1 + ',' + b1 + ')';
            }
        }
### 实现 Input 输入框的焦点事件 对于 input 输入框来说,可以通过 jQuery 来监听其获得焦点失去焦点这两个重要的交互事件。当用户点击进入输入框时会触发获得焦点事件 (focus),而当用户移开或切换到其他地方则会触发失去焦点事件 (blur)[^1]。 #### 使用 jQuery 处理 Focus Blur 事件 为了更好地管理这些行为,在 HTML 中定义好具有特定 ID 的 input 元素是非常必要的: ```html <input id="testInput" type="text"> ``` 接着利用 jQuery 提供的功能来编写相应的 JavaScript 代码片段如下所示: - **获得焦点事件** 通过 `focus()` 方法可以轻松地为指定的选择器绑定获得焦点后的回调函数。每当目标元素被激活即意味着它获得了用户的注意力并准备接收数据录入操作[^2]。 ```javascript $('#testInput').focus(function(){ console.log('The element has received focus.'); }); ``` - **失去焦点事件** 同样地,`blur()` 函数用于检测何时发生了离开当前活动状态的情况——也就是失去了光标的定位位置。这通常发生在用户完成了编辑动作之后转而去访问页面上的另一个组件之时。 ```javascript $('#testInput').blur(function(){ console.log('The element lost its focus.'); }); ``` 上述两段脚本展示了怎样分别捕捉这两种不同类型的 UI 变化情况,并且可以在实际项目开发过程中根据需求进一步扩展逻辑处理部分的内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值