萬盛學電腦網

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

仿 IE 資訊列:可關閉、動畫滑入的頂部通知欄純 JS 實作

效果預覽

  • 頁面載入後從頂部平滑滑入
  • 支援關閉按鈕,關閉後可選「本次會話不再顯示」
  • IE6 相容(含 `expression` hack),現代瀏覽器使用 `position: fixed`
  • 零依賴、約 2 KB(未壓縮)

核心架構:`InformationBar` 類別

function InformationBar() {
  this.displayFreq = 'always'; // 'always' | 'session'
  this.content = '<a href="javascript:InformationBar.close()"><img src="close.gif" style="width:14px;height:14px;float:right;border:0;margin-right:5px" /></a>';
  this.barRef = null;
  this.barHeight = 0;
}

InformationBar.prototype.setContent = function(html) {
  this.content += html;
  document.write('<div id="informationbar" style="top:-500px">' + this.content + '</div>');
};

InformationBar.prototype.animateToView = function() {
  const bar = this.barRef;
  const currentTop = parseInt(bar.style.top, 10);
  if (currentTop < 0) {
    bar.style.top = (currentTop + 5) + 'px';
    setTimeout(() => this.animateToView(), 50);
  } else {
    bar.style.top = '0';
    // IE6 fixed 模擬
    if (document.all && !window.XMLHttpRequest) {
      bar.style.setExpression('top', 'document.compatMode=="CSS1Compat"? document.documentElement.scrollTop+"px" : body.scrollTop+"px"');
    }
  }
};

InformationBar.close = function() {
  const bar = document.getElementById('informationbar');
  if (bar) bar.style.display = 'none';
  if (InformationBar.prototype.displayFreq === 'session') {
    document.cookie = 'infobarshown=1;path=/';
  }
};

InformationBar.prototype.initialize = function() {
  if (this.displayFreq === 'session' && document.cookie.indexOf('infobarshown') !== -1) return;
  this.barRef = document.getElementById('informationbar');
  this.barHeight = this.barRef.offsetHeight;
  this.barRef.style.top = (-this.barHeight) + 'px';
  this.animateToView();
};

window.onunload = function() { this.barRef = null; };

使用範例

<script>
const bar = new InformationBar();
bar.setContent('敬告:明天中午 12 點天降錢雨,請備好麻袋! <a href="#">購買麻袋</a>');
bar.initialize();
// bar.setFrequency('session'); // 可選:本次會話只顯示一次
</script>

CSS 樣式(可自行美化)

#informationbar {
  position: fixed;
  left: 0; width: 100%;
  text-indent: 5px; padding: 5px 0;
  background: #fffde7;           // 淡黃
  border-bottom: 1px solid #000;
  font: bold 12px Verdana, sans-serif;
  z-index: 9999;
}
* html #informationbar {        /* IE6 hack */
  position: absolute;
  width: expression(document.compatMode=="CSS1Compat"? document.documentElement.clientWidth+"px" : body.clientWidth+"px");
}

現代化改良建議(ES6+)

class InfoBar {
  constructor({ freq = 'always', closeIcon = '✕', zIndex = 9999 } = {}) {
    this.freq = freq;
    this.zIndex = zIndex;
    this._createBar(closeIcon);
  }

  _createBar(closeIcon) {
    this.bar = document.createElement('div');
    this.bar.id = 'info-bar';
    this.bar.style.cssText = `
      position:fixed; top:-100px; left:0; right:0; z-index:${this.zIndex};
      background:#fff3cd; border-bottom:1px solid #ffc107;
      padding:8px 16px; font:14px/1.5 system-ui; transition:top .3s ease;
    `;
    this.bar.innerHTML = `
      
      
    `;
    document.body.appendChild(this.bar);
    this.bar.querySelector('#info-close').onclick = () => this.close();
  }

  show(html) {
    if (this.freq === 'session' && document.cookie.includes('infobarshown')) return;
    this.bar.querySelector('#info-msg').innerHTML = html;
    requestAnimationFrame(() => this.bar.style.top = '0');
  }

  close() {
    this.bar.style.top = '-100px';
    if (this.freq === 'session') document.cookie = 'infobarshown=1;path=/;max-age=2592000';
  }
}

// 用法
const bar = new InfoBar({ freq: 'session' });
bar.show('系統維護通知:今晚 02:00-04:00 暫停服務 <a href="/notice">詳情</a>');

無障礙與 SEO 加分項

  • `role="alert"` 或 `aria-live="polite"` 讓螢幕閱讀器即時朗讀。
  • 關閉按鈕加 `aria-label="關閉通知"`。
  • 色彩對比達 WCAG AA(如 `#856404` on `#fff3cd`)。
  • 避免 `document.write`,改用 `appendChild` 確保 CSP 相容。

結語

這個輕量級通知欄完美復刻 IE 資訊列體驗,同時修正了原始碼的 `document.write`、全域汙染、IE6 hack 等技術債。現代專案建議採用 ES6 Class 重寫版,搭配 CSS Transition 取代 `setTimeout` 動畫,效能與維護性雙贏。

copyright © 萬盛學電腦網 all rights reserved