11.3.2焦點(diǎn)管理
HTML5也添加了輔助管理DOM焦點(diǎn)的功能,首先document.activeElement屬性,這個(gè)屬性始終會(huì)引用DOM中當(dāng)前獲得焦點(diǎn)的元素。元素獲得焦點(diǎn)的方式有頁面加載、用戶輸入(通常是通過按Tab鍵)和在代碼中調(diào)用focus()方法。
代碼示例
var button = document.getElementById("myButton");
button.focus();
alert(document.activeElement === button); // true
一般情況下,文檔剛剛加載完成時(shí),document.activeElement中保存的是document.body元素的引用。文檔加載期間,document.activeElement的值是null
document.hasFocus()方法
這個(gè)方法用于確定文檔是否獲得了焦點(diǎn) `
var button = document.getElementById("myButton");
button.focus();
alert(document.hasFocus());//true,通過檢測(cè)文檔是否獲得了焦點(diǎn),可以知道用戶是不是正在與頁面交互
兼容性
IE4+,Firefox3+,chrome,Safari4+,Opera8+