DIV CSS 佈局教程網

用原生 JavaScript 打造彈出層與遮罩效果
編輯:關於JavaScript     

彈出層是網頁裡最常見的互動元件之一:登入框、確認視窗、燈箱效果,背後都是同一套結構——一個半透明遮罩加上一個置中的內容層。這篇用原生 JavaScript 從零組裝一個可重複使用的元件。

一、建立遮罩層

遮罩的做法是動態產生一個 div,鋪滿整個可捲動區域,設為半透明黑色,層級壓在內容之上。

_createCover: function () {
    var newMask = document.createElement("div");
    newMask.id = this._mark;
    newMask.style.position = "absolute";
    newMask.style.zIndex = "100";
    _scrollWidth = Math.max(document.body.scrollWidth, document.documentElement.scrollWidth);
    _scrollHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
    newMask.style.width = _scrollWidth + "px";
    newMask.style.height = _scrollHeight + "px";
    newMask.style.top = "0px";
    newMask.style.left = "0px";
    newMask.style.background = "#000";
    newMask.style.filter = "alpha(opacity=50)";
    newMask.style.opacity = "0.50";
    newMask.style.display = 'none';
    document.body.appendChild(newMask);
    this._cover = newMask;
}

這裡取 body 與 documentElement 的 scrollWidth/scrollHeight 中的最大值,是為了處理不同瀏覽器在 quirks mode 下的差異。

二、建立彈出層

_createFloater: function (html) {
    var newDiv = document.createElement("div");
    newDiv.id = this._id;
    newDiv.style.position = "absolute";
    newDiv.style.zIndex = "9999";
    newDivWidth = 400;
    newDivHeight = 200;
    newDiv.style.width = newDivWidth + "px";
    newDiv.style.height = newDivHeight + "px";
    newDiv.style.top = (document.body.scrollTop + document.body.clientHeight / 2 - newDivHeight / 2) + "px";
    newDiv.style.left = (document.body.scrollLeft + document.body.clientWidth / 2 - newDivWidth / 2) + "px";
    newDiv.style.padding = "5px";
    newDiv.style.display = 'none';
    newDiv.innerHTML = html;
    document.body.appendChild(newDiv);
    this._floater = newDiv;
}

置中的算法是「視窗中心座標減去自身一半尺寸」。注意這裡先把捲動距離加回來,因為 position: absolute 是相對於文件而非視窗定位。

三、滾動時保持置中

addjustPosition: function () {
    this._floater.style.top = (document.body.scrollTop + document.body.clientHeight / 2 - newDivHeight / 2) + "px";
    this._floater.style.left = (document.body.scrollLeft + document.body.clientWidth / 2 - newDivWidth / 2) + "px";
}

頁面捲動時,absolute 定位的元素會跟著跑掉,所以要監聽 scroll 事件重新計算位置;關閉時則要記得移除監聽,否則會留下無解的幽靈事件。

this._fS = BindAsEventListener(this, this.addjustPosition);
addEventHandler(window, "scroll", this._fS);
// 隱藏後需要
removeEventHandler(window, "scroll", this._fS);

四、完整元件

var Floater = (function () {
    var me = Class.create();
    me.prototype = {
        initialize: function (options) {
            this._fS = BindAsEventListener(this, this.addjustPosition);
            this.setOptions(options);
        },
        setOptions: function (options) {
            this.options = options || {};
            this._id = options.id;
            this._mark = 'mark';
        },
        show: function (html, options) {
            options = options || {};
            if (!this._cover) {
                this._createCover();
            }
            if (!this._floater) {
                this._createFloater(html);
            }
            if (options.saveOpt) {
                this._saveOption = options.saveOpt;
                this.bindSaveEvent();
            }
            this._bindScrollEvent();
            this.addjustPosition();
            this._floater.style.display = '';
            this._cover.style.display = '';
            this.isShow = true;
        },
        insert: function (html, opts, att) {
            var _e = document.createElement("div"), _t;
            _e.innerHTML = html;
            for (var k in opts) {
                _e[k] = opts[k];
            }
            _t = this._floater.querySelector('[' + att + ']');
            if (_t) {
                _t.appendChild(_e);
            }
        },
        getFloater: function () {
            if (this._floater) {
                return this._floater;
            }
        },
        bindSaveEvent: function () {
            this._saveElem = this._floater.querySelector('[' + this._saveOption.elem + ']');
            if (this._saveElem) {
                addEventHandler(this._saveElem, "click", this._saveOption.handler);
            }
        },
        _bindScrollEvent: function () {
            addEventHandler(window, "scroll", this._fS);
        },
        hide: function () {
            this.isShow = false;
            this.destory();
        },
        destory: function () {
            removeEventHandler(window, "scroll", this._fS);
            if (this._saveElem) {
                removeEventHandler(this._saveElem, "click", this._saveOption.handler);
            }
            if (this._cover) {
                document.body.removeChild(this._cover);
            }
            if (this._floater) {
                document.body.removeChild(this._floater);
            }
            this._cover = null;
            this._floater = null;
        }
    };
    return me;
})();

這個結構的優點是職責清楚:show 負責顯示、hide/destory 負責清理、insert 提供動態插入內容的能力,而事件綁定與移除成對出現。

五、幾個值得改進的地方

用 position: fixed 會省很多事。fixed 定位是相對於視窗而非文件,置中不必加 scrollTop,捲動時也不會跑掉,整個 scroll 監聽都可以省下來。範例用 absolute 是為了相容很舊的 IE。

置中改用 CSS 更乾脆。把彈出層設為 position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%),不必知道元素尺寸就能置中,也就不需要 newDivWidth/newDivHeight 這兩個寫死的變數。

destory 的字樣建議改成 destroy。拼字錯誤雖然不影響執行,但會讓 API 看起來不專業。

無障礙是原範例完全沒處理的部分。彈出層開啟時應該鎖住背景捲動、把焦點移入彈出層並限制 Tab 停留其中(focus trap)、關閉後把焦點還給原本的觸發元素,同時加上 role="dialog" 與 aria-modal="true"。這些不是加分項,而是讓鍵盤與螢幕閱讀器使用者也能正常操作的必要的條件。

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