html浏览器标题闪动,网页标题title闪动提示效果实现方法

本文详细介绍了如何通过AJAX和JavaScript实现网页标题动态提示新消息的功能,以及在遇到全角半角字符宽度差异导致的显示问题时的解决方案。针对IE浏览器title属性只读的问题,提出了使用try...catch进行特殊处理的方法,确保在火狐和Chrome之外,IE浏览器也能正常工作。提供的代码示例展示了完整的实现过程。
摘要由CSDN通过智能技术生成

通过网页title来提示用户有新消息,很小巧实用的功能。

思路分析:通过ajax访问后台,若有新消息,则将网页的title替换为 提示信息 ,并与空格来回切换。

例:【你有新消息】与【     】切换。提示内容弄是动态的,所以替换文字的空格数目也是算出的。这里用全角的空格。但是如果提示消息中有‘数字'等半角字符的话就会出现问题。全角的空格比半角的1的宽度要宽的多。这样的话,闪动起来看着就不是很舒服;解决方法就是用全角的空格替换全角的字符,半角的空格替换半角的字符。

但是document.title=' ';不论半角空格有多少个,浏览器只显示一个。用 的话,它原样输出;只能用var t=document.getelementsbytagname('title')[0]。获取title dom对象,通过 t.innerhtml=' '来修改。

但会这么顺利么,当然不会。ie总会出来捣乱。在ie浏览器下title的innerhtml是只读的(不光是title,其它的如:col, colgroup, frameset, html, style, table, tbody, tfoot, thead, tr的innerhtml属性是只读的)。如果强制赋值的话会出现“未知的运行时错误”。目前没有找到很到的办法,只能加上try{}catch(e){}对它进行特殊处理了。

网页标题title闪动提示效果的完整代码:

复制代码 代码示例:

var flashtitleplayer = {

start: function (msg) {

this.title = document.title;

if (!this.action) {

try {

this.element = document.getelementsbytagname('title')[0];

this.element.innerhtml = this.title;

this.action = function (ttl) {

this.element.innerhtml = ttl;

};

} catch (e) {

this.action = function (ttl) {

document.title = ttl;

}

delete this.element;

}

this.toggletitle = function () {

this.action('【' + this.messages[this.index = this.index == 0 ? 1 : 0] + '】欢迎访问简明现代魔法');

};

}

this.messages = [msg];

var n = msg.length;

var s = '';

if (this.element) {

var num = msg.match(/\w/g);

if (num != null) {

var n2 = num.length;

n -= n2;

while (n2 > 0) {

s += " ";

n2--;

}

} // (jquery中文网 www.jquerycn.cn)

}

while (n > 0) {

s += ' ';

n--;

};

this.messages.push(s);

this.index = 0;

this.timer = setinterval(function () {

flashtitleplayer.toggletitle();

}, 1000);

},

stop: function () {

if (this.timer) {

clearinterval(this.timer);

this.action(this.title);

delete this.timer;

delete this.messages;

}

}

};

function flashtitle(msg) {

flashtitleplayer.start(msg);

}

function stopflash() {

flashtitleplayer.stop();

}

说明:

火狐,chrome下没问题,ie当提示消息中有一个或没有半角字符时没问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值