DIV CSS 佈局教程網

輕量版遮罩彈出層:幾十行代碼搞定登錄彈窗
編輯:關於JavaScript     

下面這段代碼並不是 Bootstrap 的遮罩,只是一個簡單版的遮罩效果——Bootstrap 那套結構相對繁瑣。如果你偏愛 Bootstrap 的完整風格,可以參考另一篇「完全版:Bootstrap 彈出層遮罩」。

HTML 結構

<div class="theme-popover">
<div class="theme-poptit">
<a href="javascript:void(0);" title="關閉" class="close">×</a>
<h3>登錄 是一種態度</h3>
</div>
<div class="theme-popbod dform">
<form class="theme-signin" name="loginform" action="" method="post">
<ol>
<li><h4>你必須先登錄!</h4></li>
<li><strong>用戶名:</strong><input class="ipt" type="text" name="log" value="lanrenzhijia" size="20" /></li>
<li><strong>密碼:</strong><input class="ipt" type="password" name="pwd" value="***" size="20" /></li>
<li><input class="btn btn-primary" type="submit" name="submit" value=" 登 錄 " /></li>
</ol>
</form>
</div>
</div>
<div class="theme-popover-mask"></div>

關鍵 CSS

裡面的內容樣式可以根據自己的需求調整:

.theme-popover-mask {
    z-index: 9998;
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: #000;
    opacity: 0.4;
    filter: alpha(opacity=40);
    display: none;
}
.theme-popover {
    z-index: 9999;
    position: fixed;
    top: 50%; left: 50%;
    width: 660px;
    height: 360px;
    margin: -180px 0 0 -330px;   /* 用負 margin 實現水平垂直居中 */
    border-radius: 5px;
    border: solid 2px #666;
    background-color: #fff;
    display: none;
    box-shadow: 0 0 10px #666;
}

這裡的居中技巧比較傳統:先定位到 50%/50%,再用「寬高一半」的負 margin 往回拉。優點是兼容性極好,缺點是尺寸寫死,如果彈窗高度不固定就得換成 translate 方案。

jQuery 交互

點擊觸發元素出現,點擊右上角按鈕關閉:

jQuery(document).ready(function ($) {
    $('.theme-login').click(function () {
        $('.theme-popover-mask').fadeIn(100);
        $('.theme-popover').slideDown(200);
    });

    $('.theme-poptit .close').click(function () {
        $('.theme-popover-mask').fadeOut(100);
        $('.theme-popover').slideUp(200);
    });
})

整份實現下來不到三十行有效代碼,適合中小型項目快速接入。若要進一步完善,建議再補上「點擊遮罩層關閉」與「ESC 鍵關閉」兩個交互,並在打開時給 body 加 overflow: hidden 鎖住背景滾動。

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