萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

原生 JavaScript 實現右下角彈窗動畫效果

效果描述

頁面載入或點擊按鈕時,從右下角滑出一個半透明通知層,支援展開/收合動畫與手動關閉。適用於新訊息提醒、公告推送等場景。

完整代碼結構

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>右下角彈窗示例</title>
<style>
body { background:#333; font-family: Microsoft JhengHei, sans-serif; }
#winpop {
    width: 200px; height: 0;
    position: fixed; right: 0; bottom: 0;
    border: 1px solid #999; overflow: hidden;
    display: none; background: #fff;
    box-shadow: 0 0 10px rgba(0,0,0,0.3);
}
#winpop .title {
    width: 100%; height: 30px; line-height: 30px;
    background: #ffcc00; font-weight: bold; text-align: center;
    position: relative;
}
#winpop .close {
    position: absolute; right: 8px; top: 4px;
    color: #333; cursor: pointer; font-weight: bold;
}
#winpop .con {
    padding: 15px; text-align: center; color: #f00;
    font-weight: bold; text-decoration: underline;
}
#silu { position: fixed; right: 10px; bottom: 10px; color: #999; }
</style>
</head>
<body>
<div id="silu">
    <button id="btnToggle">測試彈窗</button>
</div>

<div id="winpop">
    <div class="title">
        您有新訊息
        <span class="close">×</span>
    </div>
    <div class="con">未讀訊息 (1)</div>
</div>

<script>
var winpop = document.getElementById('winpop');
var btn = document.getElementById('btnToggle');
var timer = null;
var isOpen = false;

function togglePop() {
    clearInterval(timer);
    if (!isOpen) {
        winpop.style.display = 'block';
        animateHeight(0, 100, 10, function() { isOpen = true; });
    } else {
        animateHeight(100, 0, 10, function() {
            winpop.style.display = 'none';
            isOpen = false;
        });
    }
}

function animateHeight(from, to, step, callback) {
    var current = from;
    var direction = to > from ? 1 : -1;
    timer = setInterval(function() {
        current += step * direction;
        if ((direction === 1 && current >= to) || (direction === -1 && current <= to)) {
            current = to;
            clearInterval(timer);
            callback && callback();
        }
        winpop.style.height = current + 'px';
    }, 15);
}

btn.onclick = togglePop;
winpop.querySelector('.close').onclick = togglePop;

// 頁面載入 800ms 後自動彈出
setTimeout(togglePop, 800);
</script>
</body>
</html>

核心邏輯解析

  1. 固定定位:position:fixed; right:0; bottom:0 確保始終貼合視窗右下角。
  2. 高度動畫:animateHeight 以固定步長遞增/遞減 height,配合 overflow:hidden 實現滑動效果。
  3. 狀態控制:isOpen 防止動畫進行中重複觸發。
  4. 自動觸發:setTimeout 延遲彈出,避免頁面載入瞬間干擾用戶。

現代化改良建議

  • 改用 CSS transition: height 0.3s ease + max-height 替代 JS 定時器,效能更好、代碼更簡潔。
  • 引入 IntersectionObserver 或頁面可見性 API 控制顯示時機。
  • 支援多訊息佇列、自動輪播、響應式寬度。
copyright © 萬盛學電腦網 all rights reserved