DIV CSS 佈局教程網

兼容主流瀏覽器的 jQuery + CSS 遮罩層實作範例
編輯:JQuery特效代碼     

本文示範一個相容主流瀏覽器的遮罩層效果:點擊「註冊」後出現半透明黑色遮罩,上方顯示註冊框,此時無法操作頁面其他元素;點擊「隨便逛逛」後遮罩消失。

要點分析

1. 註冊框始終水平、垂直居中,即使捲動、縮放頁面或調整視窗大小也不受影響。主要由 CSS 控制:以 position:fixed 讓它相對瀏覽器視窗定位,再用 top:50%; left:50%; margin:-210px 0 0 -310px; 完成置中。

2. 縮放或調整視窗時,遮罩層需始終覆蓋整個文檔並充滿視窗。兩個關鍵屬性:JS 的 window.screen.availHeight 與 jQuery 的 $(document.body).outerHeight(true)。前者用於 IE 縮放後仍能充滿視窗。

HTML

<div id="wrap">
    <div id="rbox"><a class="go" href="#" onclick="return false;">先逛逛>></a></div>
    <div id="mask"></div>
    <div class="content">
        <div id="usertie">
             <span>
                <a id="register" href="#" onclick="return false;">注冊</a>
            </span>
        </div>
    </div>
</div>

CSS

a{ text-decoration:none; color:#fff;}
#rbox{
    width:620px; height:420px; position:fixed; top:50%; left:50%;
    margin:-210px 0 0 -310px; border-radius:8px; background-color:#999;
    z-index:3; display:none;
}
#mask{
    background-color:#000; position:absolute; top:0; left:0; display:none; z-index:2;
}
#register{ z-index:1; color:blue;}
.content{ width:800px; height:auto; margin:0 auto;}

JS

$(function(){
    //點擊注冊
    $("#register").click(function(){
        if(window.screen.availHeight > $(document.body).outerHeight(true)){
             $("#mask").show().css({"opacity":"0.5","width":"100%","height":window.screen.availHeight});
        }else{
             $("#mask").show().css({"opacity":"0.5","width":"100%","height":$(document.body).outerHeight(true)});
        }
        $("#rbox").show();
    });
    //根據視窗變化調整遮罩尺寸
    $(window).resize(function(){
        if($("#mask").css("width")!=0){
             $("#mask").css("width","100%");
             if(window.screen.availHeight > $(document.body).outerHeight(true)){
                 $("#mask").css({"opacity":"0.5","width":"100%","height":window.screen.availHeight});
             }else{
                 $("#mask").css({"opacity":"0.5","width":"100%","height":$(document.body).outerHeight(true)});
             }
        }
    });
    $(".go").click(function(){
        $("#mask").hide();
        $("#rbox").hide();
    });
});

如此一來,遮罩層便能始終覆蓋整個視窗,註冊框也能保持置中,功能完成。

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