gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 13:09:35 24 4
gpt4 key购买 nike

请解释 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com