代码之家  ›  专栏  ›  技术社区  ›  Cameron

使用JavaScript旋转文档标题

  •  1
  • Cameron  · 技术社区  · 14 年前

    我希望使用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 回复  |  直到 5 年前
        1
  •  1
  •   casablanca    14 年前

    现在,你每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
    }
    
        2
  •  3
  •   Dr.Molle    14 年前
    $(document).ready(function() {
            var titles=['title1','title2','title3'];
    
            setInterval(function()
            {     
                  $(document).attr('title', titles[0]);
                  titles.push(titles.shift());
            },
            2000);
    
        });
    
        3
  •  1
  •   AlexPriceAP    14 年前

    好吧,你可以不用像这样的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;
    }
    

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

        4
  •  0
  •   Philip    11 年前

    这就是我用莫勒博士的解决方案得出的结论。

    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_循环。