DIV CSS 佈局教程網

原生 JavaScript 打造圖片燈箱:從選擇器到鍵盤操作的完整實作
編輯:JavaScript綜合知識     

點擊縮圖後弹出大圖、可左右翻頁、按 Esc 關閉——這就是燈箱(Lightbox)。本文完整拆解一個原生實作,其中幾個技巧在別的專案裡也用得上。

技巧一:一次宣告多個變數

var sScrollTop = document.body.scrollTop || document.documentElement.scrollTop,
    sWindow_h  = document.documentElement.clientHeight,
    t_h        = parseInt(this.getCss(this.getId('gy_photoBox_head'), 'height')),
    hold_h     = sWindow_h - t_h - 20,
    width      = this.nImgWidth,
    height     = this.nImgHeight;

用一個 var 串接宣告,比每行都寫 var 更精簡,也能避免在迴圈中反覆宣告而拖慢速度。同時這裡用 body.scrollTop || documentElement.scrollTop 兼容不同瀏覽器的捲動量讀取方式。

技巧二:用計時器為 resize 節流

視窗尺寸改變時,resize 會以極高頻率觸發。加上短暫的 setTimeout 就能有效合併:

windowResize: function(){
    var _that = this, _timer = null;
    window.onresize = function(){
        clearTimeout(_timer);
        _timer = setTimeout(function(){
            if(_that.tools.getId('gy_photoBox')){
                _that.setBoxCss();
            }
        }, 100);
    };
}

技巧三:圖片載入的雙回呼處理

/**
 * src     圖片網址
 * success 載入成功的回呼
 * error   載入失敗的回呼
 */
imgLoading: function(opt){
    var _img = new Image(), _that = this;
    _img.onload = function(){
        _that.nImgWidth  = this.width;
        _that.nImgHeight = this.height;
        if(typeof opt.success == 'function'){
            setTimeout(function(){ opt.success(); }, 300);
        }
    };
    _img.onerror = function(){
        if(typeof opt.error) opt.error();
    };
    // 注意:src 一定要放在 onload 之後指定,否則 IE 會出錯
    _img.src = opt.src;
}

「先綁事件、再設 src」是圖片預載的鐵則。若順序顛倒,圖片來自快取時可能載入完成得比事件綁定還快,導致 onload 永遠不觸發。這個技巧讓燈箱能在顯示前先知道圖片的真實尺寸,據此計算縮放比例與居中位置。

自製輕量選擇器

元件的入口接受 CSS 選擇器字串,因此實作裡附了一個小型 selector 函式,支援 #id、.class、標籤與后代/子代查詢。它會先嘗試 document.querySelectorAll,不支援時才退回手寫的遍歷比對:

var elemStr = str.replace(/(^\s+)|(\s+$)/, '');
if(document.querySelectorAll){
    var dom = document.querySelectorAll(elemStr);
    for(var n = 0, len = dom.length; n < len; n++) elem.push(dom[n]);
} else {
    /* 舊瀏覽器的手寫後備實作 */
}

今天所有目標瀏覽器都支援 querySelectorAll,這段後備程式已無必要,但「先試標準 API、不支援才後退」的設計思路仍然值得參考。

互動細節:鍵盤操作

keyEvent: function(){
    var _that = this;
    document.onkeydown = function(e){
        var e = e || window.event;
        switch(e.keyCode){
            case 37:   // 左方向鍵 → 上一張
                if(_that.nIndex != 0 && _that.tools.getId('gy_photoBox_prev')){
                    _that.nIndex--; _that.imgChange();
                } break;
            case 39:   // 右方向鍵 → 下一張
                if(_that.nIndex != (_that.nLen - 1) && _that.tools.getId('gy_photoBox_next')){
                    _that.nIndex++; _that.imgChange();
                } break;
            case 27:   // Esc → 關閉
                _that.removeBox(); break;
        }
    };
}

支援方向鍵與 Esc 是燈箱必備的基本能力,少了它使用者就得反覆把手移回滑鼠。

居中與縮放計算

setBoxCss: function(){
    var doc = document,
        nScrollTop = doc.body.scrollTop || doc.documentElement.scrollTop,
        nWindow_h  = doc.documentElement.clientHeight,
        eBox_head_h = this.tools.getId('gy_photoBox_head').clientHeight,
        eBox = this.tools.getId('gy_photoBox'),
        eBoxPadding = 10,
        hold_h = nWindow_h - eBoxPadding - 50 - eBox_head_h,
        width = this.nImgWidth, height = this.nImgHeight;

    // 圖片高於可用空間時按比例縮放
    if(this.nImgHeight > hold_h){
        height = hold_h;
        width = Math.ceil(this.nImgWidth * (height / this.nImgHeight));
    }
    // 让整个盒子在页面中垂直水平居中
    this.tools.setCss(eBox, {
        'width': width + 'px',
        'height': eBox_head_h + height + 'px',
        'margin-left': -(width + eBoxPadding) / 2 + 'px',
        'top': nScrollTop + (nWindow_h - height - eBoxPadding) / 2 + 'px'
    });
}

幾個必須補強的地方

1. 背景不可捲動:元件有處理(把 documentElement 的 overflow 設為 hidden),但關閉時要記得還原,否則頁面會永久鎖住無法捲動。

2. 焦點管理:燈箱打開後,焦點應該移進彈窗內並被鎖住(focus trap),關閉後再還給原本的觸發元素。原實作未處理,鍵盤使用者會 Tab 到背後的頁面元素上。

3. ARIA 標記:彈窗容器應加上 role="dialog" 與 aria-modal="true",並有可讀的 aria-label。

4. 點擊遮罩關閉:原實作只有右上角的關閉鈕,加上「點擊遮罩層關閉」會更符合使用者預期。

5. 載入失敗要有替代圖:實作裡有處理(顯示 error.png),這點做得很好,值得沿用。

總結來說,這個元件的骨架完整且思路清楚:預載取得尺寸 → 依視窗計算縮放與居中 → 渲染並顯示 → 支援鍵盤與 resize。掌握這條主線之後,加上無障礙與焦點管理,就能成為一個真正可上線的燈箱元件。

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