利用 document.activeElement 可獲取當前擁有焦點的元素,結合 tagName、id、name 等屬性即可精確判斷。
var active = document.activeElement;
console.log(active.tagName); // 標籤名,大寫如 'INPUT'
console.log(active.id); // id 屬性
console.log(active.name); // name 屬性
var tag = document.activeElement.tagName.toLowerCase();
if (tag === 'body' || tag === 'html') {
document.body.style.imeMode = 'disabled';
}
<input name="a" type="text" value="測試a" onclick="test()">
<input name="b" type="text" value="測試b" onclick="test()">
<script>
function test() {
var src = document.activeElement;
alert('控件 ' + (src.name || src.id) + ' 獲取焦點');
}
</script>
activeElement 在 IE9+、現代瀏覽器均支援。iframe,需遞歸進入 iframe.contentDocument.activeElement。