2010-11-25 62 views
0

我正在尋找使用JS旋轉網頁文檔標題。例如:使用JavaScript旋轉文檔標題

更改爲Domain.comNew Messgae - Domain.com,然後返回到Domain.com等,這與Facebook在使用聊天時使用新郵件的方式非常相似。

我已經看過使用SetInterval但它只有一個表達式?是否有可能改變這個或使用SetInterval錯誤的函數來使用?

 $(document).ready(function() { 

      setInterval(function() 
      { 
        $(document).attr('title', 'New Message — Domain.com'); 
      }, 
      2000); 

     }); 
+1

這將您的標題更改爲新郵件&....,之後始終以相同的mesage不會返回到默認的標題,你應該存儲您的默認標題在一些window.mytitle全局變量 – Marcin 2010-11-25 16:57:09

+0

你能告訴我請。謝謝 – Cameron 2010-11-25 16:58:48

回答

1

現在,您每2秒鐘就會設置相同的新標題,即在第一次更改後您不會看到更改。你需要存儲兩個狀態之間的舊題和替代,顯示新老冠軍:

var oldTitle, timerId; 

function flashTitle(newTitle) { 
    var state = false; 
    oldTitle = document.title; // save old title 
    timerId = setInterval(flash, 2000); 

    function flash() { 
    // switch between old and new titles 
    document.title = state ? oldTitle : newTitle; 
    state = !state; 
    } 
} 

function clearFlash() { 
    clearInterval(timerId); 
    document.title = oldTitle; // restore old title 
} 
1

那麼你可以做到這一點,而無需使用JavaScript庫是這樣的...

var title = document.getElementsByTagName('title'); 
var msg1 = "Domain.com"; 
var msg2 = "New Message - Domain.com" 
var current; 
var titleChange; 

function changeTitle(){ 
    if(current == msg1){ 
    title = msg2; 
    current = msg2; 
    }else{ //If the current title isn't equal to the value of msg1 
    title = msg1; 
    current = msg1; 
    } 
titleChange = setTimeout("changeTitle()", 1000); 
} 

function stopChangingTitle(){ 
clearTimeout(titleChange); 
title = msg1; 
} 

我不能保證,上面的代碼將工作,但它應該工作!

2
$(document).ready(function() { 
     var titles=['title1','title2','title3']; 

     setInterval(function() 
     {  
       $(document).attr('title', titles[0]); 
       titles.push(titles.shift()); 
     }, 
     2000); 

    }); 
0

這是我想出了利用Dr.Molle的解決方案。

function changeTitle (mytitle,count) { 
    console.log(title_change); 
    console.log(count); 
    if (count >= 1) { 
     var titles = [$('title').attr('data-title'),mytitle]; 
     title_change = setInterval(function(){  
      $(document).attr('title', titles[0]); 
      titles.push(titles.shift()); 
     }, 
     1000); 


    } else { 
     clearInterval(title_change); 
     //clearTimeout(title_change); 
     title_change = false; 
    } 

     return false; 

} 

但是我確實發現,當我宣佈,我似乎無法得到的setInterval各地停止循環功能外title_change。當count超過> = 1時,進程啓動,但當它返回0時,clearInterval和clearTimeout不會停止change_loop。