javascript - document.hidden 与 document.hasFocus() 之间的区别

标签 javascript html dom dom-events

请解释 document.hidden、HTML5 页面可见性 API 和 document.hasFocus() 之间的区别。我正在做一个项目,该项目在选项卡未聚焦时弹出 HTML5 桌面通知。我有点困惑该使用哪个。

最佳答案

hidden attribute定义如下:

On getting, the hidden attribute MUST return true if the Document contained by the top level browsing context (root window in the browser's viewport) is not visible at all. The attribute MUST return false if the Document contained by the top level browsing context is at least partially visible on at least one screen.

If the defaultView of the Document is null, on getting, the hidden attribute MUST return true.

hasFocus method是这样定义的

The hasFocus() method on Document objects must return true if the Document's browsing context is focused, and all its ancestor browsing contexts are also focused, and the top-level browsing context has the system focus. If the Document has no browsing context or if its browsing context has no top-level browsing context, then the method will always return false.

例如,如果您在前台选项卡中打开一个页面,然后打开另一个窗口,该选项卡将(或可能)仍然部分可见,因此 hidden 返回 false。但是,新窗口有焦点,因此 hasFocus() 为选项卡返回 false。

如果您运行以下代码片段,iframe 内的文档将可见但不会获得焦点(此 stackoverflow 页面获得焦点):

document.body.innerHTML = 
  '<p>hidden: ' + document.hidden + '</p>' +
  '<p>hasFocus: ' + document.hasFocus() + '</p>';

但在另一个中,由于您单击 iframe 内的按钮,它既可见又聚焦:

document.getElementsByTagName('input')[0].onclick = function() {
  document.body.innerHTML = 
    '<p>hidden: ' + document.hidden + '</p>' +
    '<p>hasFocus: ' + document.hasFocus() + '</p>';
};
<input type="button" value="Click me!" />

关于javascript - document.hidden 与 document.hasFocus() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29331979/

相关文章:

javascript - $(window).height() 不起作用

css - 将绝对 div 定位在相对 div 下面

javascript - polymer 属性不在元素中

php - Onsubmit anchor 链接

javascript - 在 600 长度后检查最近的点 (".") 然后删除点后的所有文本

javascript - "Cut and Paste"- 使用 Javascript 在 DOM 中移动节点

javascript - 什么是 "out of DOM"元素?

javascript - 如何解决平板电脑上的 col-md 无法正确显示的问题

javascript - WebRTC 视频限制不起作用

javascript - 鼠标悬停时div打开和关闭速度