jQuery弹簧插件编写基础之“又见弹窗”

2020-05-29 07:21:05易采站长站整理

      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: 'rgba(0,0,0,0.4)',
      overflow: 'hidden'
    });
    
    //窗口区域
    popWinDom = $('<div><div></div><div></div><div></div></div>').css({
      width: this.opts.width,
      height: this.opts.height,
      position: 'absolute',
      top: '30%',
      left: '50%',
      marginLeft: '-' + (this.opts.width.split('px')[0] / 2) + 'px'
    }).attr('class',this.opts.winCssName);
    
    //标题区域
    titleAreaDom = popWinDom.find('div:eq(0)')
              .text(this.opts.title)
              .attr('class',this.opts.titleCssName);
    
    //描述区域
    descAreaDom = popWinDom.find('div:eq(1)')
.text(this.opts.desc)
.attr('class',this.opts.descCssName);
    //按钮区域   
    btnAreaDom = popWinDom.find('div:eq(2)')
.attr('class',this.opts.btnAreaCssName);
    
    //插入按钮
    this.opts.btnArr.map(function(item, index) {
      btnAreaDom.append($('<button></button>')
        .text(item)
        .attr({'data-index':index, 'class':_this.opts.btnCssName})
        .on('click', function() {
          _this.opts.callback($(this).attr('data-index'));
        }));
      });
    
    this.$ele.append(popWinDom);
}
}

1. 首先命名了四个变量用来缓存我们将要创建的四个DOM,将传入的jQuery对象变形成覆盖整个窗口半透明元素;

2. 创建窗口DOM,根据传入的高、宽来设置尺寸并居中,之后另上传入的窗口CSS类名;

3. 创建标题、描述、按钮组区域,并将传入的标题、描述内容配置上去;

4. 动态加入按钮,并为按钮加上data-index的索引值。注册点击事件,点击后调用传入的回调函数,将索引值传回。

好了,我们先看下效果。调用如下:


$('#content').popWin({
width: '500',
height: '200',
title: '系统提示',
desc: '注册成功',
btnArr: ['关闭'],
callback: function(clickIndex) {
console.log(clickIndex);
}
});

可以看到一个弹窗的DOM已被渲染到页面中了,当点击关闭按钮时控制台会打印出 “0”,因为按钮组只有一个值嘛,当然是第0个了。