在 Opera、Google Chrome 和 Safari 中,使用 DOMFocusIn 事件而不是 onfocusin 事件。
在 Firefox 中,如果您需要检测元素的子元素是否获得焦点,请为 onfocus 事件使用捕获侦听器。
要检测元素何时失去焦点,请使用 onblur、onfocusout 和 DOMFocusOut 事件。
function Init () {
var form = document.getElementById ("myForm");
if ("onfocusin" in form) { // Internet Explorer
// the attachEvent method can also be used in IE9,
// but we want to use the cross-browser addEventListener method if possible
if (form.addEventListener) { // IE from version 9
form.addEventListener ("focusin", OnFocusInForm, false);
form.addEventListener ("focusout", OnFocusOutForm, false);
}
else {
if (form.attachEvent) { // IE before version 9
form.attachEvent ("onfocusin", OnFocusInForm);
form.attachEvent ("onfocusout", OnFocusOutForm);
}
}
}
else {
if (form.addEventListener) { // Firefox, Opera, Google Chrome and Safari
// since Firefox does not support the DOMFocusIn/Out events
// and we do not want browser detection
// the focus and blur events are used in all browsers excluding IE
// capturing listeners, because focus and blur events do not bubble up
form.addEventListener ("focus", OnFocusInForm, true);
form.addEventListener ("blur", OnFocusOutForm, true);
}
}
}
function OnFocusInForm (event) {
var target = event.target ? event.target : event.srcElement;
if (target) {
target.style.color = "red";
}
}
function OnFocusOutForm (event) {
var target = event.target ? event.target : event.srcElement;
if (target) {
target.style.color = "";
}
}
</script>
<body onload="Init ()">
<form id="myForm">
User name: <input type="text" value="my name"/><br />
E-mail: <input type="text" value="myname@mydomain.com"/>
</form>
</body>
更新
了另一种方式,您可以像这样进行个人控制
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('#checkboxname').addEventListener('focus', focusHandler);
});
function focusHandler(){
}
<input type="checkbox" id="checkboxname" name="checkboxname"/>