提醒:本文最后更新于 3234 天前,文中所描述的信息可能已发生改变,请仔细核实。
var changeTitle = { time: 0, originTitle: document.title, timer: null, change: function() { document.title = "~New Message Received~ " + changeTitle.originTitle; }, notify: function() { if(document.title.indexOf("~New Message Received~")) clearTimeout(changeTitle.timer); document.title = "~New Message Received~ " + changeTitle.originTitle; changeTitle.timer = setTimeout(function(){changeTitle.clear();},3000); }, flash: function() { changeTitle.timer = setTimeout(function () { changeTitle.time++; changeTitle.flash(); if (changeTitle.time % 2 === 0) { document.title = "~ ~ " + changeTitle.originTitle; }else{ document.title = "~New Message Received~ " + changeTitle.originTitle; } }, 500); }, reset: function() { clearTimeout(changeTitle.timer); document.title = changeTitle.originTitle; } };
通过以下方法可以调用:
changeTitle.change();//更改标题 changeTitle.notify();//更改标题3秒后恢复 changeTitle.flash();//闪烁标题 changeTitle.reset();//复位标题
通过监听visibilitychange,你可以完成一些有意思的动作,比如进入和离开页面时改变标题(具体应该说标签为非前置状态时改变标题,标签前置状态时改变标题):
var changeTitle={time:0,originTitle:document.title,timer:null,change:function(){document.title="~New Message Received~ "+changeTitle.originTitle},notify:function(){if(document.title.indexOf("~New Message Received~"))clearTimeout(changeTitle.timer);document.title="~New Message Received~ "+changeTitle.originTitle;changeTitle.timer=setTimeout(function(){changeTitle.reset()},3000)},flash:function(){changeTitle.timer=setTimeout(function(){changeTitle.time++;changeTitle.flash();if(changeTitle.time%2===0){document.title="~ ~ "+changeTitle.originTitle}else{document.title="~New Message Received~ "+changeTitle.originTitle}},500)},reset:function(){clearTimeout(changeTitle.timer);document.title=changeTitle.originTitle}}; document.addEventListener('visibilitychange', function() { if (document.hidden) { changeTitle.flash(); } else { changeTitle.reset(); } });
上述例子,为方便显示把changeTitle对象压缩了。
最后,为情人节干杯。
转载请注明转自:kn007的个人博客的《js改变浏览器标签标题》