首頁想放一張大尺寸重點圖,但又不想永遠佔著版面,常見的解法是讓它在頁面載入後延遲數秒浮現,停留一段時間後自動淡出。與其開新視窗(會被瀏覽器的彈出阻擋機制攔下),不如用一個覆蓋全畫面的遮罩層來做,效果可控且相容性更好。
<div id="adLayer" hidden>
<div class="adBox">
<a href="https://example.com/promo" target="_blank" rel="noopener">
<img src="/img/ad-960x600.jpg" alt="活動宣傳圖">
</a>
<button type="button" id="adClose" aria-label="關閉廣告">關閉 ×</button>
</div>
</div>
<style>
#adLayer {
position: fixed;
inset: 0;
z-index: 9999;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, .6);
}
#adLayer[hidden] { display: none; }
.adBox { position: relative; max-width: 90%; }
.adBox img { display: block; max-width: 100%; height: auto; }
#adClose {
position: absolute;
top: -14px; right: -14px;
width: 32px; height: 32px;
border: 0; border-radius: 50%;
background: #333; color: #fff;
cursor: pointer;
}
</style>
兩個 setTimeout 就能完成:一個負責在頁面載入後開啟,一個負責在開啟後關閉。把計時器 handle 留著,使用者手動關閉時記得清除,避免它之後又跑一次。
<script>
(function () {
var SHOW_DELAY = 3000; // 載入後幾毫秒彈出
var STAY_TIME = 8000; // 停留多久後自動關閉
var layer = document.getElementById('adLayer');
var closeBtn = document.getElementById('adClose');
var hideTimer = null;
function openAd() {
layer.hidden = false;
hideTimer = setTimeout(closeAd, STAY_TIME);
}
function closeAd() {
layer.hidden = true;
if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; }
}
closeBtn.addEventListener('click', closeAd);
layer.addEventListener('click', function (e) {
if (e.target === layer) closeAd(); // 點遮罩空白处也能關
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') closeAd(); // 鍵盤可操作
});
window.addEventListener('load', function () {
setTimeout(openAd, SHOW_DELAY);
});
})();
</script>
早期類似需求的寫法是把多張圖片寫進陣列,用 new Image() 預先載入避免播放時閃白,再用一個絕對定位的容器搭配 clip: rect(...) 一點一點把矩形揭露區放大,看起來就像圖片被慢慢拉開;透明層則用來做淡入淡出。那套邏輯在今天仍然有用——預先載入圖片這一步尤其值得保留,可以大幅改善大圖首次出現時的延遲。
alt。純裝飾圖給空字串,有資訊內容的圖要描述清楚。