document.activeElement 返回當前獲得焦點的 DOM 元素(IE4+、所有現代瀏覽器支援)。
<input type="text" id="textID" />
<button onclick="checkFocus()">檢查焦點</button>
function checkFocus() {
var activeEl = document.activeElement;
var targetEl = document.getElementById('textID');
if (activeEl === targetEl) {
alert('textID 目前擁有焦點 ✅');
} else {
alert('textID 未擁有焦點 ❌,當前焦點:' + (activeEl.id || activeEl.tagName));
}
}
<asp:TextBox ID="TextBox1" runat="server" />
<script>
// 客戶端 ID 與伺服端 ID 不同
var clientId = '<%= TextBox1.ClientID %>'; // 如 ctl00_Content_TextBox1
function checkServerControlFocus() {
var activeEl = document.activeElement;
var targetEl = document.getElementById(clientId);
if (activeEl === targetEl) {
console.log('伺服端控件有焦點');
}
}
// 綁定焦點事件(原生)
document.getElementById(clientId).addEventListener('focus', function() {
console.log('獲得焦點');
});
document.getElementById(clientId).addEventListener('blur', function() {
console.log('失去焦點');
});
</script>
function validateBeforeSubmit() {
var active = document.activeElement;
var form = document.getElementById('myForm');
// 如果焦點在表單外,可能是用戶誤觸提交
if (!form.contains(active)) {
// 可選:聚焦第一個錯誤欄位
var firstInvalid = form.querySelector('.invalid');
if (firstInvalid) firstInvalid.focus();
return false;
}
return true;
}
// 獲取當前聚焦元素的 jQuery 物件
var $active = $(document.activeElement);
// 獲取 ID
var activeId = $active.attr('id');
// 判斷特定元素
$('#textID').click(function() {
var isFocused = $(document.activeElement).is('#textID');
// 或
var isFocused2 = document.activeElement === this;
alert(isFocused ? '已聚焦' : '未聚焦');
});
// 監聽焦點變化(委派給 document)
$(document).on('focusin focusout', function(e) {
console.log(e.type, e.target.id, e.target.tagName);
});
| 事件 | 冒泡 | 適用場景 |
|---|---|---|
focus / blur | 不冒泡 | 單一元素監聽 |
focusin / focusout | 冒泡 | 委派監聽、表單級追蹤 |