1

我正在寻找使用 JS 旋转网页文档标题。例如:

更改为Domain.com然后New Messgae - Domain.com返回到 Domain.com 等等,非常类似于 Facebook 在使用聊天时如何处理新消息。

我已经研究过使用 SetInterval 但它只有一个表达式除外?是否可以更改此设置或使用 SetInterval 使用错误的功能?

$(document).ready(function () {

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

});
4

4 回答 4

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

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

    });
于 2010-11-25T17:11:55.687 回答
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;
}

我不能保证上面的代码可以工作,但它应该可以工作!

于 2010-11-25T17:05:15.353 回答
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
}
于 2010-11-25T17:13:15.763 回答
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;

}

但是,当我在函数之外声明 title_change 时,我确实发现我似乎无法让 setInterval 停止循环。当 count 虽然 >= 1 时,进程开始,但是当它返回为 0 时,clearInterval 和 clearTimeout 并没有停止 change_loop。

于 2014-03-06T02:43:00.973 回答