DIV CSS 佈局教程網

JavaScript 實現右下角滑出式彈窗提示
編輯:關於JavaScript     

這是一個常見於論壇與即時通訊頁面的效果:頁面右下角會有一段提示窗「長」出來,點擊標題列的叉號又能收回去。核心做法是改變容器的高度,並用 setInterval 做逐格動畫。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>右下角的彈窗</title>
<style type="text/css">
body { background:#333333; }
#winpop { width:200px; height:0; position:absolute; right:0; bottom:0;
          border:1px solid #999999; margin:0; padding:1px; overflow:hidden;
          display:none; background:#FFFFFF; }
#winpop .title { width:100%; height:20px; line-height:20px; background:#FFCC00;
                 font-weight:bold; text-align:center; font-size:12px; }
#winpop .con { width:100%; height:80px; line-height:80px; font-weight:bold;
               font-size:12px; color:#FF0000; text-decoration:underline;
               text-align:center; }
.close { position:absolute; right:4px; top:-1px; color:#FFFFFF; cursor:pointer; }
</style>
<script type="text/javascript">
function tips_pop() {
    var MsgPop = document.getElementById("winpop");
    var popH = parseInt(MsgPop.style.height);
    if (popH == 0) {
        MsgPop.style.display = "block";
        show = setInterval("changeH('up')", 2);
    } else {
        hide = setInterval("changeH('down')", 2);
    }
}

function changeH(str) {
    var MsgPop = document.getElementById("winpop");
    var popH = parseInt(MsgPop.style.height);
    if (str == "up") {
        if (popH <= 100) {
            MsgPop.style.height = (popH + 4) + "px";
        } else {
            clearInterval(show);
        }
    }
    if (str == "down") {
        if (popH >= 4) {
            MsgPop.style.height = (popH - 4) + "px";
        } else {
            clearInterval(hide);
            MsgPop.style.display = "none";
        }
    }
}

window.onload = function () {
    document.getElementById('winpop').style.height = '0px';
    setTimeout("tips_pop()", 800);
};
</script>
</head>
<body>
<div id="winpop">
  <div class="title">您有新的消息
    <span class="close" onclick="tips_pop()">X</span></div>
  <div class="con">未讀資訊(1)</div>
</div>
</body>
</html>

這份實作有幾個可以改良的地方。第一,overflow:hidden 是讓內容隨高度一起被裁切、產生「捲動」錯覺的關鍵,不能省。第二,用字串形式呼叫 setInterval("changeH('up')")等價於又一次 eval,應改傳函式參照並用閉包帶入方向參數。第三,定時器間隔 2 毫秒遠低於瀏覽器實際可處理的頻率(瀏覽器會將最小間隔限制在約 4 毫秒以上),容易造成動畫不順。

現代的等價寫法可以簡短許多:

pop.style.transition = "height .3s ease";
pop.style.height = open ? "100px" : "0";

把動畫交給 CSS,JavaScript 只負責切換狀態,程式碼量與效能都更好。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved