1. 程式人生 > 程式設計 >JavaScript中document.activeELement焦點元素介紹

JavaScript中document.activeELement焦點元素介紹

目錄
  • 1、預設焦點在body
  • 2、文字框手動獲取焦點
  • 3、通過focus獲取焦點
  • 4、tab切換焦點
  • 5、document.hasFocus()判斷是否獲取焦點

前言:

有時需要獲取頁面焦點在哪個元素上,通過焦點可以判斷使用者是否在操作頁面等資訊。以前不太方便,要自己記錄,html5增加了document.activeElement屬性可以獲取到當前啟用的焦點。

1、預設焦點在body

頁面載入後,document.activeElement是在body上:

console.log(document.activeElement);

// 控制檯列印:

//    body

2、文字框手動獲取焦點

獲取焦點,最常見的就是表單元素了,這裡以文字

框為例:

<input type="text" id="name" />

當把游標放到文字框內時,在控制檯檢視document.activeElement物件。

document.activeElement:

JavaScript中document.activeELement焦點元素介紹

就是上面獲取焦點的文字框。

3、通過focus獲取焦點

ERckRE了手動放到文字框內,讓文字框獲取焦點,也可以通過focus()方法讓文字框獲取焦點。

<input type="text" id="name" />

<script type="text/">

    // 文字框獲取角度

    document.querySelector("#name").focus();

    console.log(document.activeElement);

    // 火狐瀏覽器控制檯列印:

    //    <input id="name" type="text">

</script>

4、tab切換焦點

中可以通過tab切換焦點,再來一個按鈕試試:

<input type="text" id="name" />

<button>點我</button>

為了方便檢視效果,設定一個定時器,5秒後列印document.activeElement:

setTimeout(() => {

    console.log(document.activeElement);

    // 火狐瀏覽器控制檯列印:

    //    <button>

},5000);

訪問頁面,通過tab切換到button按鈕上,然後檢視控制檯輸出:

tab切換焦點:

JavaScript中document.activeELement焦點元素介紹

5、docu客棧ment.hasFocus()判斷是否獲取焦點

同樣的設定定時器檢視:

setTimeout(() => {

    console.log程式設計客棧(document.hasFocus());

},5000);
  • 訪問頁面時,如果切換到其他頁面,5秒後回來檢視就是false。表示使用者並沒有在操作頁面。
  • 如果停留在頁面或者再頁面操作,那麼返回true,通過這個可以判斷使用者是否在操作頁面。

到此這篇關於 Scriptdocument.activeELement焦點元素介紹的文章就介紹到這了,更多相關 JavaScriptdocument.activeELement焦點元素內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!