欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript中document.activeELement焦點(diǎn)元素介紹

 更新時(shí)間:2021年11月24日 11:15:42   作者:快樂編程  
這篇文章主要給大家分享 JavaScript中document.activeELement焦點(diǎn)元素介紹,下面文章圍繞了document.activeElement屬性展開詳細(xì)內(nèi)容,需要的朋友可以參考一下,希望對(duì)大家有所幫助

前言:

有時(shí)需要獲取頁面焦點(diǎn)在哪個(gè)元素上,通過焦點(diǎn)可以判斷用戶是否在操作頁面等信息。以前不太方便,要自己記錄,html5增加了document.activeElement屬性可以獲取到當(dāng)前激活的焦點(diǎn)。

1、默認(rèn)焦點(diǎn)在body

頁面加載后,document.activeElement是在body上:

console.log(document.activeElement);

// 控制臺(tái)打?。?

//    body

2、文本框手動(dòng)獲取焦點(diǎn)

獲取焦點(diǎn),最常見的就是表單元素了,這里以文本框?yàn)槔?/strong>

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

當(dāng)把光標(biāo)放到文本框內(nèi)時(shí),在控制臺(tái)查看document.activeElement對(duì)象。

document.activeElement:

就是上面獲取焦點(diǎn)的文本框。

3、通過focus獲取焦點(diǎn)

除了手動(dòng)放到文本框內(nèi),讓文本框獲取焦點(diǎn),也可以通過focus()方法讓文本框獲取焦點(diǎn)。

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

<script type="text/javascript">

    // 文本框獲取角度

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

    console.log(document.activeElement);

    // 火狐瀏覽器控制臺(tái)打?。?

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

</script>

4、tab切換焦點(diǎn)

網(wǎng)頁中可以通過tab切換焦點(diǎn),再來一個(gè)按鈕試試:

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

<button>點(diǎn)我</button>

為了方便查看效果,設(shè)置一個(gè)定時(shí)器,5秒后打印document.activeElement:

setTimeout(() => {

    console.log(document.activeElement);

    // 火狐瀏覽器控制臺(tái)打印:

    //    <button>

}, 5000);

訪問頁面,通過tab切換到button按鈕上,然后查看控制臺(tái)輸出:

tab切換焦點(diǎn):

5、document.hasFocus()判斷是否獲取焦點(diǎn)

同樣的設(shè)置定時(shí)器查看:

setTimeout(() => {

    console.log(document.hasFocus());

}, 5000);
  • 訪問頁面時(shí),如果切換到其他頁面,5秒后回來查看就是false。表示用戶并沒有在操作頁面。
  • 如果停留在頁面或者再頁面操作,那么返回true,通過這個(gè)可以判斷用戶是否在操作頁面。

到此這篇關(guān)于 JavaScriptdocument.activeELement焦點(diǎn)元素介紹的文章就介紹到這了,更多相關(guān) JavaScriptdocument.activeELement焦點(diǎn)元素內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論