在Opera,谷歌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="[email protected]"/>
</form>
</body>
更新 另一種方式,你可以做這樣的單獨控制
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#checkboxname').addEventListener('focus', focusHandler);
});
function focusHandler(){
}
<input type="checkbox" id="checkboxname" name="checkboxname"/>
感謝您詳細的解答。這將如何工作複選框?用戶可以選中複選框而不是點擊它。我似乎無法得到與您提供的功能一起工作。 – TroyS 2013-05-02 17:52:27
它將適用於表單中的所有元素,並且event.target會爲您提供控件名稱..然後您可以使用event.target來執行您的活動 – 2013-05-02 17:56:58
剛剛更新了答案 – 2013-05-02 18:01:13