html5增加了document.activeElement属性可以获取到当前激活的焦点。页面加载后,document.activeElement是在body上:
console.log(document.activeElement); // 控制台打印: // body
获取焦点,最常见的就是表单元素了,这里以文本框为例:
<input type="text" id="name" />
当把光标放到文本框内时,在控制台查看document.activeElement对象。
document.activeElement:

就是上面获取焦点的文本框。
除了手动放到文本框内,让文本框获取焦点,也可以通过focus()方法让文本框获取焦点。
<input type="text" id="name" />
<script type="text/javascript">
// 文本框获取角度
document.querySelector("#name").focus();
console.log(document.activeElement);
// 火狐浏览器控制台打印:
// <input id="name" type="text">
</script>
网页中可以通过tab切换焦点,再来一个按钮试试:
<input type="text" id="name" /> <button>点我</button>
为了方便查看效果,设置一个定时器,5秒后打印document.activeElement:
setTimeout(() => {
console.log(document.activeElement);
// 火狐浏览器控制台打印:
// <button>
}, 5000);
访问页面,通过tab切换到button按钮上,然后查看控制台输出:
tab切换焦点:

同样的设置定时器查看:
setTimeout(() => {
console.log(document.hasFocus());
}, 5000);
false。表示用户并没有在操作页面。免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理