DIV CSS 佈局教程網

可關閉的漂浮視窗:讓廣告隨捲軸移動並能自行收起
編輯:關於JavaScript     

漂浮視窗的做法是「用 absolute 定位 + 定時器」。每次頁面捲動後,重新把視窗的 top 設為「目前捲動量 + 視窗高度 - 廣告高度」,它就會一直黏在右下角;再附一個關閉按鈕把 display 設為 none 即可。

完整程式碼

<!DOCTYPE html>
<html>
<head>
<title>可關閉的漂浮視窗</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>

<body style="background-color:#09C">
<div id="ShowAD" style="position:absolute;z-index:100;">
  <div style="width:135px;height:18px;font-size:14px;font-weight:bold;
              text-align:left;cursor:pointer;" onClick="closead();">
    <font color="#ff0000">關閉</font><br/>
    點擊這裡,關閉廣告!!!
    <br><a href="/jscss/"><img src="img/ads1.png" alt="廣告"></a>
  </div>
</div>

<script type="text/javascript">
// 相容不同 doctype 下的 body 參照
var bodyfrm = (document.compatMode.toLowerCase() == "css1compat")
            ? document.documentElement : document.body;

var adst = document.getElementById("ShowAD").style;

// 初始位置:視窗右下(530 是廣告高度,22 是預留邊距)
adst.top = (bodyfrm.clientHeight - 530 - 22) + "px";
// 若要靠右:adst.left = (bodyfrm.clientWidth - 155) + "px";

// 捲動時重新定位
function moveR() {
    adst.top = (bodyfrm.scrollTop + bodyfrm.clientHeight - 530 - 22) + "px";
    // adst.left = (bodyfrm.scrollLeft + bodyfrm.clientWidth - 155) + "px";
}
setInterval("moveR();", 80);

function closead() {
    adst.display = 'none';
}
</script>

<!-- 用來撐出頁面高度,方便測試捲動效果 -->
<div id="Content" style="height:1200px;"></div>
</body>
</html>

註解掉的那兩行 adst.left 就是水平方向的調整;把 top 那行註解掉、改用 left,視窗就會變成隨左右捲動的水平浮動橫幅。數值 530 與 155 請換成你自己的廣告尺寸。

為什麼現在不該這樣寫

  • 用 setInterval 輪詢捲動位置非常浪費:每 80 毫秒就改一次 style,即使使用者根本沒在捲。請改用 scroll 事件並搭配 requestAnimationFrame 節流。
  • position:fixed 才是正解:它天生相對視窗定位,捲動時自動保持不動,一行 CSS 就取代整個 moveR 與定時器:
#ShowAD {
    position: fixed;
    right: 0;
    bottom: 22px;
    z-index: 100;
}

其他要補的細節

  • cursor:hand 是 IE 專屬,標準寫法是 cursor:pointer。
  • 用 <font> 設定顏色已不符標準,請改用 CSS。
  • 關閉後應該記住:把狀態寫進 localStorage,否則使用者每次換頁都被同一個視窗追著跑,體驗極差。
  • 可親和性:關閉鈕請用 <button> 並加上 aria-label="關閉廣告",鍵盤使用者才關得掉。
  • 行動裝置:漂浮視窗容易擋住內容,請預留足夠邊距或在小螢幕上直接隱藏。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved