更多例子
将“onfocus”与“onblur”事件一起使用:
<input type="text" onfocus="focusFunction()" onblur="blurFunction()">
尝试一下
清除焦点上的输入字段:
<input type="text" onfocus="this.value=''" value="Blabla">
尝试一下
事件委托:将addEventListener()的useCapture参数设置为true:
<form id="myForm">
<input type="text" id="myInput">
</form>
<script>
var x = document.getElementById("myForm");
x.addEventListener("focus", myFocusFunction, true);
x.addEventListener("blur", myBlurFunction, true);
function myFocusFunction() {
document.getElementById("myInput").style.backgroundColor = "yellow";
}
function myBlurFunction() {
document.getElementById("myInput").style.backgroundColor = "";
}
</script>
尝试一下
事件委托:使用focusin事件(Firefox不支持):
<form id="myForm">
<input type="text" id="myInput">
</form>
<script>
var x = document.getElementById("myForm");
x.addEventListener("focusin", myFocusFunction);
x.addEventListener("focusout", myBlurFunction);
function myFocusFunction() {
document.getElementById("myInput").style.backgroundColor = "yellow";
}
function myBlurFunction() {
document.getElementById("myInput").style.backgroundColor = "";
}
</script>
尝试一下