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"
};
};
};
}
初始状态
获得焦点onfocus
失去焦点
总之,这俩个事件是相对的,记住焦点就记住它们了