--- title: document.hasFocus slug: Web/API/Document/hasFocus tags: - API - DOM - 参考 - 方法 - 焦点 translation_of: Web/API/Document/hasFocus ---
{{ ApiRef }}
Document.hasFocus()
方法返回一个 {{jsxref("Boolean")}},表明当前文档或者当前文档内的节点是否获得了焦点。该方法可以用来判断当前文档中的活动元素是否获得了焦点。
focused = document.hasFocus();
如果当前文档的活动元素获得了焦点,返回 true
,否则返回false。
<!DOCTYPE html> <html> <head> <style type='text/css'> #message { font-weight: bold; } </style> <script type='text/javascript'> setInterval("CheckPageFocus()", 200); function CheckPageFocus() { var info = document.getElementById("message"); if (document.hasFocus()) { info.innerHTML = "该页面获得了焦点."; } else { info.innerHTML = "该页面没有获得焦点."; } } function OpenWindow() { window.open ("http://developer.mozilla.org/", "mozdev", "width=640, height=300, left=150, top=260"); } </script> </head> <body> document.hasFocus 演示<br /><br /> <div id="message">等待用户操作</div><br /> <button onclick="OpenWindow()">打开一个新窗口</button> </body> </html>
{{ CompatibilityTable() }}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | {{ CompatVersionUnknown() }} | {{ CompatGeckoDesktop("1.9") }} | 6.0 | {{ CompatNo() }} | {{ CompatVersionUnknown() }} |
Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | {{ CompatUnknown() }} | {{ CompatGeckoMobile("1.9") }} | {{ CompatUnknown() }} | {{ CompatNo() }} | {{ CompatUnknown() }} |
{{ languages( { "en": "en/DOM/document.hasFocus","es": "es/DOM/element.hasFocus", "fr": "fr/DOM/document.hasFocus", "ja": "ja/DOM/document.hasFocus", "pl": "pl/DOM/document.hasFocus" } ) }}