document.hasFocus() & $(window).blur()

- $(window).blur()

jquery方法:

1.当内嵌iframe时,会触发

2.当弹出上传框时,会触发

3.当出现弹出“是否允许麦克风或摄像头”时,会触发

- document.hasFocus():用于检测文档(或文档内的任一元素)是否获取焦点

1.当内嵌iframe时,不触发

2.当弹出上传框时,会触发

3.当出现弹出“是否允许麦克风或摄像头”时,会触发

方法chrome ie firefox safari  opare
hasFocus() 30.0 6.0 3.0 Yes 23.0

 

- document.activeElement:当前文档获取焦点的元素js对象 

 诡异问题:document.activeElement 为 HTMLBodyElement; 但 document.hasFocus() 返回 false;

 场景描述:内嵌外部iframe页面,通过angular 路由跳转到parent window出现上面诡异问题;parent window页面跳转到内嵌iframe的页面正常;

 解决方法:判断路由,非iframe路由强制focus button按钮

        $("button#focus").get(0).focus();

 猜测问题点:document.activeElement当页面没有焦点的时候 默认为 HTMLBodyElement;所以,iframe跳回主页面时并没有焦点;但是主页面跳转到iframe时会自动iframe获取焦点;

- 可以获取焦点的元素(浏览器行为,差异比较大)

  • HTMLAnchorElement/HTMLAreaElement with an href
  • HTMLInputElement/HTMLSelectElement/HTMLTextAreaElement/HTMLButtonElement but not with disabled (IE actually gives you an error if you try), and file uploads have unusual behaviour for security reasons
  • HTMLIFrameElement (though focusing it doesn't do anything useful). Other embedding elements also, maybe, I haven't tested them all.
  • Any element with a tabindex != -1
  • div contentEditable = true
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        .box{
            width: 100px;
            height: 100px;
            background-color: #EEEEEE;
            display: inline-block;
        }
    </style>
    <script type="text/javascript">
        window.onload = function () {
            document.onkeyup = function () {
                console.log(document.activeElement);
            }
        }
    </script>
</head>
<body>
<div class="box" tabindex="-1">tabindex = -1</div>
<div class="box" tabindex="2">tabindex = 2</div>
<span class="box" style="display: block"> display: block</span>
<div class="box" contenteditable="true">contenteditable="true"</div>
<button disabled>disabled</button>
<button>undisabled</button>
<iframe src="wwww.baidu.com" width="100" height="100"></iframe>
</body>
</html>

 

posted @ 2018-04-08 14:23  田木夕  阅读(1116)  评论(0编辑  收藏  举报