萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現網頁標題欄閃爍提示(新消息通知效果)

核心原理

利用 document.title 定時切換顯示「【新消息】」與原標題,配合 setInterval/setTimeout 形成閃爍動畫,適用於 Web 聊天、通知系統。

版本一:物件字面量寫法(教學版)

var newMessageRemind = {
  _step: 0,
  _title: document.title,
  _timer: null,

  show: function() {
    var baseTitle = this._title.replace('【 】', '').replace('【新消息】', '');
    var self = this;

    this._timer = setTimeout(function() {
      self.show(); // 遞歸調用形成循環
      self._step++;
      if (self._step === 3) self._step = 1;

      if (self._step === 1) document.title = '【 】' + baseTitle;
      if (self._step === 2) document.title = '【新消息】' + baseTitle;
    }, 800);

    return [this._timer, this._title];
  },

  clear: function() {
    clearTimeout(this._timer);
    document.title = this._title;
  }
};

// 使用方式
newMessageRemind.show();  // 開始閃爍
newMessageRemind.clear(); // 停止並恢復原標題

版本二:IIFE 閉包優化版(推薦生產環境)

優點:無全局汙染、變數私有化、用 setInterval 替代遞歸 setTimeout、代碼更精簡。

var newMessageRemind = (function() {
  var i = 0;
  var originalTitle = document.title;
  var timer = null;

  return {
    show: function() {
      timer = setInterval(function() {
        i++;
        if (i === 1) document.title = '【新消息】' + originalTitle;
        if (i === 2) document.title = '【 】' + originalTitle;
        if (i === 3) i = 0;
      }, 800);
    },

    stop: function() {
      clearInterval(timer);
      document.title = originalTitle;
    }
  };
})();

// 完整可運行 Demo
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>頁面標題閃爍 Demo</title>
</head>
<body>
  <button id="btnStop">停止閃爍</button>
  <script>
  var newMessageRemind = (function() {
    var i = 0, title = document.title, loop;
    return {
      show: function() {
        loop = setInterval(function() {
          i++;
          if (i === 1) document.title = '【新消息】' + title;
          if (i === 2) document.title = '【 】' + title;
          if (i === 3) i = 0;
        }, 800);
      },
      stop: function() {
        clearInterval(loop);
        document.title = title;
      }
    };
  })();

  newMessageRemind.show();
  document.getElementById('btnStop').onclick = function() {
    newMessageRemind.stop();
  };
  </script>
</body>
</html>

實戰建議

  • 頁面隱藏時(document.hidden)啟動閃爍,頁面顯示時自動停止,避免干擾正在閱覽的用戶。
  • 結合 Page Visibility API 實現智能通知:
document.addEventListener('visibilitychange', function() {
  if (document.hidden) newMessageRemind.show();
  else newMessageRemind.stop();
});
copyright © 萬盛學電腦網 all rights reserved