DIV CSS 佈局教程網

原生 JavaScript 打造圖片彈窗燈箱交互效果
編輯:關於JavaScript     

本文分享以純原生 JavaScript 實作圖片彈窗(Lightbox)的完整思路與關鍵技巧,包含效能優化、事件節流與圖片載入處理。

一、合併 var 宣告提升效能

用一個 var 一次宣告多個變數,比每個變數都寫 var 更有效率:

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;

二、以定時器做事件節流

在 window.onresize 事件中定義定時器,可避免事件被過於頻繁地觸發:

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 [String] 圖片的地址
   @ success [Function] 圖片載入成功的回呼函式
   @ error [Function] 圖片載入失敗的回呼函式
*/
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();
    }
  }
  // 注意:要放在 onload 事件下面,否則 IE 會出現 BUG
  _img.src = opt.src;
}

完整原始碼

下方為整個彈窗元件的完整實作,包含簡單選擇器、彈窗構造函式、覆蓋層、樣式設定、鍵盤事件與工具函式等:

/*
author:laoguoyong
*/
(function(){
  // 簡單的選擇器,支援 '#id'、'.class'、'p'、後代與子代選擇
  var selector = function(str){
    var elem = [];
    function _getId(id){ return document.getElementById(id); }
    function _getByClassName(className,parent){
      var class_array = [],
          node = parent != undefined && parent.nodeType==1 ? parent.getElementsByTagName('*') : document.getElementsByTagName('*'),
          reg = new RegExp("(^|\\s)"+className+"(\\s|$)");
      for(var n=0,i=node.length;n<i;n++){
        if(reg.test(node[n].className)){ class_array.push(node[n]); }
      }
      return class_array;
    }
    function _getDom(s){
      var array_elem = [];
      if (s.indexOf('#')==0){ array_elem.push(_getId(s.slice(1))); }
      else if(s.indexOf('.')==0){ array_elem = array_elem.concat(_getByClassName(s.slice(1))); }
      else{
        var tag = document.getElementsByTagName(s);
        for(var n=0,i=tag.length;n<i;n++){ array_elem.push(tag[n]); }
      }
      return array_elem;
    }
    // 後代/子代查詢
    function _query(array_elem,r){
      var node = array_elem,
          type_name = node[0].match(/\#/) ? 'id_'+node[0].slice(1) : node[0].match(/\./) ? 'className_'+node[0].slice(1) : 'tagName_'+node[0],
          child = _getDom(node[1]),
          type = type_name.split('_'),
          len = document.getElementsByTagName('*').length,
          reg = new RegExp("(^|\\s)"+type[1]+"(\\s|$)");
      for(var i=0,j=child.length;i<j;i++){
        var par = child[i].parentNode;
        for(var n=0;n<len;n++){
          if(par.nodeType == 9){ break; }
          if(reg.test(par[type[0]])){ elem.push(child[i]); break; }
          else{ if(r == '>') break; par = par.parentNode; }
        }
      }
    }
    // 介面
    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{
      var split = /[\>\s]/g.exec(elemStr);
      if(split){
        var node = elemStr.split(split[0]);
        _query(node,split[0]);
      }else{
        elem = elem.concat( _getDom(elemStr) );
      }
    }
    return elem;
  };
  // 彈窗功能構造函式
  function LGY_photoBox(option){
    this.opt = option;
    this.oTarget = typeof option.target == 'object' ? option.target : selector(option.target);
    if(!this.oTarget) return;
    this.nLen = this.oTarget.length; // 總個數
    this.aBigimg_src = [];           // 大圖資料陣列
    this.aTitle = [];                // 標題資料陣列
    this.nIndex = 0;                 // 索引
    this.nImgWidth = 0;              // 動態取得圖片寬
    this.nImgHeight = 0;             // 動態取得圖片高
    this.nDelay = 0.2;
    this.intit();
  }
  LGY_photoBox.prototype = {
    intit:function(){
      var _that = this;
      this.getData();
      for(var n=0;n<this.nLen;n++){
        this.oTarget[n].index = n;
        this.oTarget[n].onclick = function(e){
          _that.createCover();
          _that.tools.setCss(document.documentElement,{'height':'100%','overflow-y':'hidden','overflow-x':'hidden'});
          _that.nIndex = this.index;
          _that.firstLoad(_that.aBigimg_src[_that.nIndex],function(){
            _that.createBoxDom();
            _that.tools.getId('gy_photoBox_close').onclick = function(){ _that.removeBox(); }
            _that.btnIsShow();
            _that.btnPrev();
            _that.btnNext();
            _that.imgChange(_that.aBigimg_src[_that.nIndex]);
          });
          _that.windowResize();
          _that.keyEvent();
          return false;
        }
      }
    },
    createBoxDom:function(){
      var doc = document, exHtml = '', boxHtml = doc.createElement('div');
      boxHtml.id = 'gy_photoBox';
      doc.body.appendChild(boxHtml);
      if(typeof this.opt.appendHTML == 'string'){ exHtml = this.opt.appendHTML; }
      boxHtml.innerHTML = '<div id="gy_photoBox_prev"></div>'+
        '<div id="gy_photoBox_next"></div>'+
        '<span id="gy_photoBox_close"></span>'+
        '<div id="gy_photoBox_head">'+exHtml+'</div>'+
        '<div id="gy_photoBox_main">'+
          '<img id="gy_photoBox_img_loading" src="blank.gif" />'+
          '<img id="gy_photoBox_img" />'+
          '<div id="gy_photoBox_infor">'+
            '<span id="gy_photoBox_num"><strong id="gy_photoBox_index"></strong>/'+this.nLen+'</span>'+
            '<p id="gy_photoBox_title"></p>'+
          '</div>'+
        '</div>';
    },
    createCover:function(){
      var doc = document, coverHtml = doc.createElement('div');
      coverHtml.id = 'gy_photoBox_cover';
      doc.body.appendChild(coverHtml);
      this.tools.setCss(this.tools.getId('gy_photoBox_cover'),{'height':(doc.body.scrollTop || doc.documentElement.scrollTop)+(doc.documentElement.clientHeight)+'px'});
    },
    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'});
      this.tools.setCss(this.tools.getId('gy_photoBox_main'),{'width':width+'px','height':height + 'px'});
      this.tools.setCss(this.tools.getId('gy_photoBox_cover'),{'height':nScrollTop+doc.documentElement.clientHeight+'px'});
    },
    removeBox:function(){
      var doc = document;
      if(this.tools.getId('gy_photoBox')){ doc.body.removeChild(this.tools.getId('gy_photoBox')); }
      if(this.tools.getId('gy_photoBox_cover')){ document.body.removeChild(this.tools.getId('gy_photoBox_cover')); }
      this.tools.setCss(document.documentElement,{'height':'auto','overflow-y':'auto','_overflow-y':'scroll','overflow-x':'auto'});
    },
    getData:function(){
      for(var n=0;n<this.nLen;n++){
        var src = this.oTarget[n].getAttribute('href'),
            title = this.oTarget[n].getAttribute('title');
        this.aBigimg_src.push(src);
        if(!title) title = '';
        this.aTitle.push(title);
      }
    },
    btnIsShow:function(){
      this.tools.setCss(this.tools.getId('gy_photoBox_prev'),{'display':'block'});
      this.tools.setCss(this.tools.getId('gy_photoBox_next'),{'display':'block'});
      if(this.nIndex == 0) this.tools.setCss(this.tools.getId('gy_photoBox_prev'),{'display':'none'});
      if(this.nIndex == (this.nLen-1)) this.tools.setCss(this.tools.getId('gy_photoBox_next'),{'display':'none'});
    },
    imgChange:function(){
      var _that = this,
          _src = this.aBigimg_src[this.nIndex],
          eLoadingTips = this.tools.getId('gy_photoBox_img_loading'),
          eImg = this.tools.getId('gy_photoBox_img'),
          eTitle = this.tools.getId('gy_photoBox_title'),
          eInfor = this.tools.getId('gy_photoBox_infor');
      this.tools.setCss(eLoadingTips,{'display':'block'});
      this.tools.setCss(eInfor,{'display':'none'});
      this.btnIsShow();
      this.imgLoading({
        'src':_src,
        'success':function(){
          _that.tools.setCss(eLoadingTips,{'display':'none'});
          _that.tools.setCss(eInfor,{'display':'block'});
          eImg.src = _src;
          eTitle.innerHTML = _that.aTitle[_that.nIndex];
          _that.tools.getId('gy_photoBox_index').innerHTML = (_that.nIndex+1);
          _that.setBoxCss();
          _that.tools.setCss(_that.tools.getId('gy_photoBox'),{'visibility':'visible'});
          if(_that.tools.getId('gy_photoBox_firstLoad')){
            document.body.removeChild(_that.tools.getId('gy_photoBox_firstLoad'));
          }
          if(typeof _that.opt.onChange == 'function'){
            _that.opt.onChange({'src':_src,'index':_that.nIndex,'title':_that.aTitle[_that.nIndex]});
          }
        },
        'error':function(){
          setTimeout(function(){
            _that.tools.setCss(eLoadingTips,{'display':'none'});
          },200);
          eImg.src = 'gyPhotoBox/error.png';
          eTitle.innerHTML = '暫無相關圖片';
          _that.nImgWidth = 400;
          _that.nImgHeight = 300;
          _that.setBoxCss();
          _that.tools.setCss(_that.tools.getId('gy_photoBox'),{'visibility':'visible'});
          if(_that.tools.getId('gy_photoBox_firstLoad')){
            document.body.removeChild(_that.tools.getId('gy_photoBox_firstLoad'));
          }
        }
      });
    },
    btnPrev:function(){
      var _that = this;
      this.tools.getId('gy_photoBox_prev').onclick = function(){
        _that.nIndex--;
        _that.imgChange();
      }
    },
    btnNext:function(){
      var _that = this;
      this.tools.getId('gy_photoBox_next').onclick = function(){
        _that.nIndex++;
        _that.imgChange();
      }
    },
    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:{ _that.removeBox(); };break;
        }
      }
    },
    firstLoad:function(src,callback){
      var html = document.createElement('div');
      html.id = 'gy_photoBox_firstLoad';
      document.body.appendChild(html);
      this.tools.setCss(this.tools.getId('gy_photoBox_firstLoad'),{'top':(document.body.scrollTop || document.documentElement.scrollTop)+(document.documentElement.clientHeight/2) +'px'});
      if(typeof callback == 'function'){ callback(); }
    },
    windowResize:function(){
      var _that = this, _timer = null;
      window.onresize = function(){
        clearTimeout(_timer);
        _timer = setTimeout(function(){
          if( _that.tools.getId('gy_photoBox')){ _that.setBoxCss(); }
        },100);
      }
    },
    tools:function(){
      return{
        getEvent:function(e){ return e || window.event; },
        getTarget:function(e){ return e.target || e.srcElement; },
        preventDefault:function(e){ e.preventDefault ? e.preventDefault() : e.returnValue = false; },
        getId:function(id){ return document.getElementById(id); },
        getCss:function(node,value){ return node.currentStyle ? node.currentStyle[value] : getComputedStyle(node,null)[value]; },
        setCss:function(node,val){ for(var v in val){ node.style.cssText += ';'+ v +':'+val[v]; } }
      }
    }()
  };
  window.LGY_photoBox = LGY_photoBox;
})();

最終效果圖:

這個元件完整示範了原生 JavaScript 在互動效果上的強大能力,包含效能優化與跨瀏覽器相容處理,值得細細研究。

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