如何根据浏览器标签的状态动态更改网站图标?

3

感谢您的关注。在大多数浏览器中,当选中标签时,我的网站图标具有高对比度(看起来不错),但是当未选中标签时,对比度较低(难以看清)。

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

2个回答

4
为了做到这一点,您可以使用窗口的focus和blur事件。
$(window).focus(function() {
    var link = document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = 'http://www.stackoverflow.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.stackoverflow.com/favicon.ico';
    document.getElementsByTagName('head')[0].appendChild(link);
});

或者使用更短的HTML代码来设置网站图标,如下所示:

或者使用以下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");
});

只是提醒一下:你的两个解决方案都是用 JQuery 编写的。第二个方案简短而精炼! - Paurian
哎呀,我用jquery用惯了,都忘了我在使用它了。 - JD Davis

3

最简单的方法

    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" />


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接