通過網頁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){}對它進行特殊處理了
分享下源代碼:
複製代碼代碼如下:
<script type="text/javascript" language="javascript">
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--;
}
}
}
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();
}
</script>
火狐,chrome下沒問題,ie當提示消息中有一個或沒有半角字符時沒問題。