coverbox.js 2.93 KB
/*
 * Cover the show.
 * Recode in 2015/08/26
 * By van
 */

define( 'coverbox' ,function( require, exports, module ){
  var coverbox = function( opt ){
    var _this = this, cache = [], body = $("body");

    _this.opt = $.extend( {
      url: [
        'http://static.nong12.com/static/newStatic/common/images/loadingroll.gif', //加载图路径
        'http://static.nong12.com/static/newStatic/common/images/covershadow.png' //遮罩背景图路径
      ],
      load: '加载中...', //加载提示文字
      tpl: {
        boxwrap: '<div class="coverbox"></div>',
        boxinner: '<div class="coverbox-inner"></div>',
        boximg: '<p><img class="coverbox-image" src=""/></p>',
        boxword: '<span style="display:inline-block;*display:inline;*zoom:1"></span>'
      },
      time: 3 // 延时持续时间 单位: 秒 
    }, opt );

    var _url = _this.opt.url;
    var _load = _this.opt.load;
    var _tpl = _this.opt.tpl;

    function packHtml(isImg, fn, words){
      var img = isImg;
      var boxwrap = $(_tpl.boxwrap),
          boxinner = $(_tpl.boxinner),
          boximg = $(_tpl.boximg),
          boxword = $(_tpl.boxword);

      var dom = boxwrap.append(boxinner);
      typeof words == 'string' ? boxword.html(words) :
        boxword.html(_load);
      !!isImg ? boxinner.append(boximg).append(boxword) :
        boxinner.append(boxword);

      if (typeof fn == 'function'){
        fn([boxwrap, boxinner, boximg, boxword], img);
      };

      return dom;
    };

    function _append(){
      var len = cache.push(packHtml(true, _format));
      body.append( cache[len-1] );
    };
    
    function _tell(w){
      var len = cache.push(packHtml(false, _format, w));
      body.append( cache[len-1] );
      setTimeout(function(){ _remove(); }, _this.opt.time * 1000);
    };
    
    function _remove(){
      do{
        try{
          cache.shift().remove();
        }catch(e){};
      }while(cache.length);
    };

    function _format(ary, isImg){
      var wrap = ary[0],
          inner = ary[1],
          img = ary[2],
          word = ary[3];

      wrap.css({
        'position': 'fixed',
        'width': '100%',
        'height': '100%',
        'left': 0,
        'top': 0,
        //'background': 'url('+ _url[1] +')',
        'textAlign': 'center',
        'zIndex': 10000
      });
      inner.css({
        'position': 'absolute',
        'width': '100%',
        'left': 0,
        'top': '50%',
        'marginTop': -inner.height()/2,
      });
      if (isImg){
        img.find('img').attr('src', _url[0])
        word.css({
          'color': '#333',
          'margin': '10px 0 0 0'
        });
      }else {
        word.css({
          'color': '#fff',
          'background': 'rgba(0,0,0, 0.5)',
          'height': '50px',
          'font': '18px/50px "SimSun"',
          'padding': '0 20px'
        });
      }
    };

    return {
      append: _append,
      remove: _remove,
      tell: _tell
    }
  };

  return coverbox;
});