笔记:js:onfocus和onblur事件

onfocus事件

onfocus事件在对象得到焦点的时候触发。

曾经我学习时不明白焦点的定义,那就试一试就明白了 ^ _ ^
在这里插入图片描述
这个闪着蓝光,鼠标光标在的地方就是获得了焦点
当然这个蓝色其实是outline-style没有设置成none,不同浏览器显示的样式也是不一样的。
这个是事件,方法是focus();

onblur事件

onblur事件在失去焦点时触发

这里还是用之前的搜索框举例

html

<body>
    <div>
        <input type="text" id="txt" value="请输入.." />
        <button id="btn">查询</button>
    </div>
</body>

css

 <style>
        * {
            margin: 0;
            padding: 0;
        }
        div{
            margin: 150px 0 0 400px;
        }
        input {
            width: 500px;
            height: 40px;
            float: left;
            box-sizing: border-box;    
            outline-style: none;
            padding: 10px;
            
        }

        button {
            height: 40px;
            float: left;
        }
    </style>

js

window.onload = function () {
            function $(id) {
                return document.getElementById(id);
            }
            $("txt").onfocus = function () {
                if ($("txt").value == "请输入..") {
                    this.value = "";
                    this.style.color = "#09f";
                };
                $("txt").onblur = function () {
                    if ($("txt").value == "") {
                        this.value = "请输入..";
                        this.style.color = "#080"
                    };
                };
            };
}

初始状态
0
获得焦点onfocus
1
失去焦点
2
总之,这俩个事件是相对的,记住焦点就记住它们了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值