如何根据浏览器选项卡的状态动态更改我的网站图标?

How can I change my favicon dynamically depending on the state of the browser tab?

感谢观看。 In most browsers, my favicon has high contrast (looks good) when the tab is selected but low contrast (hard to see) when the tab is not selected.

大多数浏览器是否有某种通用的 "hook" 可以告诉我我的页面何时不是活动选项卡,以便我可以切换到对比度更高的图标,然后切换回常规图标该选项卡处于活动状态?

为此,您将使用 window 的焦点和模糊事件。

$(window).focus(function() {
    var link = document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = 'http://www.whosebug.com/favicon.ico';
    document.getElementsByTagName('head')[0].appendChild(link);
});

$(window).blur(function() {
    var link = document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = 'http://www.whosebug.com/favicon.ico';
    document.getElementsByTagName('head')[0].appendChild(link);
});

或者使用更短的 HTML 用于 favicon

<link id="favicon" rel="shortcut icon" type="image/png" href="favicon.png" />

$(window).focus(function() {
    $("#favicon").attr("href","favicon1.png");
});

$(window).blur(function() {
    $("#favicon").attr("href","favicon2.png");
});

最简单的方法

    var fi = document.getElementById("favicon"); 

      window.onfocus=function(){
        fi.setAttribute("href", "favicon-1.jpg");
      }

      window.onblur=function(){
        fi.setAttribute("href", "favicon-2.png");
      }
<link id="favicon" rel="shortcut icon" type="image/png" href="favicon-1.png" />