經典的定時自動關閉浮層廣告,頁面加載 5 秒後自動隱藏。包含居中定位、跨瀏覽器兼容(IE6+/現代瀏覽器)、倒計時動畫邏輯。
<style>
#sponsorAdDiv {
position: fixed; /* 現代瀏覽器 fixed 相對視口 */
/* IE6 兼容需用 absolute + expression 或 JS 計算 scroll */
display: none;
z-index: 9999;
width: 450px; height: 350px;
background: #008000;
}
</style>
<div id="sponsorAdDiv">
<table width="450" height="350" bgcolor="#008000"><tr><td>
<table width="445" height="345" bgcolor="#F0FFF0"><tr><td>
<center>Welcome!<br><br>此窗口將在 5 秒後自動關閉</center>
</td></tr></table>
</td></tr></table>
</div>
<script>
var adTime = 5; // 顯示秒數
var adCount = 0;
var adDiv, adTimer;
function initAd() {
adDiv = document.getElementById('sponsorAdDiv').style;
adDiv.display = 'block';
centerAd();
showAd();
}
function centerAd() {
var w = window.innerWidth || document.documentElement.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight;
var scrollX = window.pageXOffset || document.documentElement.scrollLeft;
var scrollY = window.pageYOffset || document.documentElement.scrollTop;
adDiv.left = (w - 450) / 2 + scrollX + 'px';
adDiv.top = (h - 350) / 2 + scrollY + 'px';
}
function showAd() {
if (adCount < adTime * 10) { // 每 100ms 一幀,共 50 幀
adCount++;
centerAd(); // 跟隨滾動居中
adTimer = setTimeout(showAd, 100);
} else {
closeAd();
}
}
function closeAd() {
adDiv.display = 'none';
clearTimeout(adTimer);
}
// 頁面加載啟動
window.onload = initAd;
// 可選:點擊關閉
// document.getElementById('sponsorAdDiv').onclick = closeAd;
</script>
position: fixed 現代瀏覽器相對視口定位,無需監聽滾動。absolute + 監聽 scroll/resize 重新計算位置(代碼中已通用寫法兼容)。setTimeout 遞歸實現倒計時幀動畫,每 100ms 更新位置。position: fixed + CSS transform: translate(-50%, -50%) 完美居中。transition 或 @keyframes,JS 僅切換 class。