DIV CSS 佈局教程網

置頂浮動工具條:附關閉按鈕的 JS 實作
編輯:關於JavaScript     

網站頂端常需要一條公告或導覽橫幅,既要在捲動時保持可見,又要讓使用者能自行關掉。這個範例示範最精簡的做法:一個 div、一個函式。

CSS

body { margin: 0px; padding: 0px; text-align: center;}
TD { FONT-SIZE: 12px; COLOR: #333;}
#toubiao { BORDER-BOTTOM: #e2e2e2 1px solid;}

樣式很克制:只定義了字級、顏色與底部分隔線。因為要浮動在頂端,其餘定位交給 HTML 結構處理。

HTML 與 JS

<SCRIPT>
function toueme(){
  document.getElementById("toubiao").style.display = "none";
}
</SCRIPT>

<DIV id=toubiao>
  <table width="100%" border="0" cellspacing="0" cellpadding="5">
    <tr>
      <td width="82%">
        <a target="_blank" href="/">
          <span style="text-decoration: none">
            <font color="#808080">懸浮在網頁頂部可關閉的工具條(浮動層),點擊可以關閉哦</font>
          </span>
        </a>
      </td>
      <td width="14%" align="right">
        <a style="CURSOR: hand" onClick="toueme()">
          <img src="../img/close3.gif" hspace="6" border=0>
        </a>
      </td>
    </tr>
  </table>
</DIV>

關閉的全部秘密就是 style.display = "none"。用 display 而非真的從 DOM 移除節點,好處是隨時可以改回 "block" 讓它重新出現,不必重建元素。

真正需要動腦的地方:position:fixed

這個範例的 div 其實是「頁面最上方的普通元素」,捲動時會跟著跑掉,並不算真正浮動。要做到「永遠貼在視窗頂端」,關鍵是 position:fixed:

#toubiao {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 9999;
  background: #f7f7f7;
  border-bottom: 1px solid #e2e2e2;
}

加上 fixed 之後,工具條會脫離文件流,頁面內容會被它蓋住。解法是幫 body 補上同等高度的 padding:

body { padding-top: 40px; }

進階:記住使用者的選擇

只關閉當次瀏覽其實不夠貼心——使用者下次進來又得關一次。用 localStorage 記住選擇,只顯示一次:

const bar = document.getElementById("toubiao");

if (localStorage.getItem("barClosed")) {
  bar.style.display = "none";
}

function closeBar() {
  bar.style.display = "none";
  localStorage.setItem("barClosed", "1");
}

若希望公告改版後能重新顯示,把 key 加上版本號即可,例如 barClosed_v2。

幾個實務細節

範例用了 <font> 標籤與 CURSOR: hand,兩者都已被 CSS 取代(color 屬性與 cursor:pointer)。另外,用 table 做版面配置也已不是好做法,改用 flex 會更靈活:

#toubiao {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px;
}

最後,關閉按鈕務必給 alt 或 aria-label,讓使用螢幕閱讀器的人知道那是什麼:

<button onClick="closeBar()" aria-label="關閉公告列">✕</button>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved