漂浮視窗的做法是「用 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 請換成你自己的廣告尺寸。
scroll 事件並搭配 requestAnimationFrame 節流。#ShowAD {
position: fixed;
right: 0;
bottom: 22px;
z-index: 100;
}
cursor:pointer。localStorage,否則使用者每次換頁都被同一個視窗追著跑,體驗極差。<button> 並加上 aria-label="關閉廣告",鍵盤使用者才關得掉。