title闪动:新消息提醒

  前些天,要实现一个功能。在后台,一些信息是要实时提醒给后台管理员。用的是通过ajax获取最新信息,然后在前台提示;原来系统自带的是弹出一个对话框,然后flash播放铃声;这种方式不是很友好,对话框弹出一会就消失了,这个页面不能最小化,不然是看不到的;另外播放铃声也得要求管理员带上耳机。
于是就想到了邮箱中来新邮件那种提示方式,闪动标题栏;
思路是:
 通过ajax访问后台,若有新消息,则将网页的title替换为 提示信息 ,并与空格来回切换;
例:【你有新消息】与【     】切换;
提示内容弄是动态的,所以替换文字的空格数目也是算出的。这里用全角的空格;
但是如果提示消息中有‘数字’等半角字符的话就会出现问题。
闪动时
【你有1条新消息】
【你有 条新消息】

var flash_title={
doc:document,
timer:null,
is_flash:false,
o_title:'',
msg:'有新消息',
message:null,
flash : function(msg){

if(this.is_flash){
this.clear();//先停止
}else{
this.o_title=this.doc.title;//保存原来的title
}
this.is_flash=true;
if(typeof(msg)=='undefined'){
msg=this.msg;
}
this.message=[msg,this.getSpace(msg)];
var th=this;
this.timer=setInterval(function(){th._flash(msg);},1000);
} ,
_flash : function(msg){
this.index=(!this.index)?1:0;
this.doc.title='【'+this.message[this.index]+'】';
},
clear : function (){
clearInterval(this.timer);
if(this.is_flash)// 如果正在闪
this.doc.title=this.o_title;//将title复原
this.is_flash=false;
},
getSpace : function (msg){
var n=msg.length;
var s='';
var num=msg.match(/\w/g);
var n2=(num!=null)?num.length:0;//半角字符的个数
n=n-n2; //全角字符个数
var t=parseInt(n2/2);
if(t>0){//两个半角替换为一个全角
n=n+t;
}
s=(n2%2)?' ':'';//如果半角字符个数为奇数
while(n>0){
s=s+' ';//全角空格
n--;
};
return s;
}
};

flash_title.flash();//默认提示
setTimeout(function(){ flash_title.flash('您有3条新消息');},5000);
setTimeout(function(){ flash_title.flash('您有30条新消息');},15000);
setTimeout(function(){ flash_title.clear();},25000);//停止

原文地址:https://www.cnblogs.com/cotty/p/2323310.html