弹窗组件的开发

一、需求分析

  开发过程中弹窗是必不可少的,如果我们每次需要弹窗都要重新开发,既浪费了人力又影响了性能,那么组件是不错的选择。

二、先写样式

  <style>

* {
  margin: 0;
  padding: 0;
}
.login {
  background: #fff;
  border: 1px solid #000;
  position: absolute;
  left: 0;
  top: 0;
}
.title {
  width: 100%;
  height: 30px;
  background: #333;
  color: #fff;
}
.title .close {
  display: block;
  float: right;
}
< / style >

  *对应的 html标签如下,先注释掉,一会动态加进body。

<!-- <div class="login">
<div class="title">
<span>111</span><span class="close">X</span>
</div>
<div class="content"></div>
</div> -->

三、body的内容

< input type= "button" value= "1" >
< input type= "button" value= "2" >
< input type= "button" value= "3" >

四、脚本

< script >
    window. onload = function() {
      var aInput = document. getElementsByTagName( 'input');
        aInput[ 0]. onclick = function() {
        var d1 = new Dialog();
        d1. init(); // 这里走默认配置
      }
      aInput[ 1]. onclick = function() {
        var d1 = new Dialog();
        d1. init({
          dir: 'right' // 自定义配置
        });
      }
    }
 
    function Dialog() {
      this. oLogin = null;
      this. settings = { // 默认配置
        w: 300,
        h: 300,
        dir: 'center'
      }
    }
    Dialog. prototype. init = function( opt) {
      extend( this. settings, opt);
      this. create();
    }
    Dialog. prototype. create = function() {
      this. oLogin = document. createElement( 'div');
      this. oLogin. className = 'login';
      this. oLogin. innerHTML = `<div class="title">
                     <span>111</span><span class="close">X</span>
                    </div>
                    <div class="content"></div>`;
       document. body. appendChild( this. oLogin);
      this. setData();
    }
    Dialog. prototype. setData = function() {
      this. oLogin. style. width = this. settings. w + 'px';
      this. oLogin. style. height = this. settings. h + 'px';
      if ( this. settings. dir == 'center') {
        this. oLogin. style. left = ( viewWidth() - this. oLogin. offsetWidth)/ 2 + 'px';
        this. oLogin. style. top = ( viewHeight() - this. oLogin. offsetHeight)/ 2 + 'px';
      } else if ( this. settings. dir == 'right') {
        this. oLogin. style. left = ( viewWidth() - this. oLogin. offsetWidth) + 'px';
        this. oLogin. style. top = ( viewHeight() - this. oLogin. offsetHeight) + 'px';
      }
    }
 
    // 合并对象
    function extend( obj1, obj2) {
      for ( var attr in obj2) {
        obj1[ attr] = obj2[ attr];
      }
    }
    // 获取可视区的宽
    function viewWidth() {
      return document. documentElement. clientWidth;
    }
    // 获取可视区的高
function viewHeight() {
return document. documentElement. clientHeight;
}
< / script >

五、运行效果图

点击第一个按钮弹出中间的弹窗;

点击第二个按钮弹出右下角的弹窗;

  

 

猜你喜欢

转载自www.cnblogs.com/hyshi/p/10901949.html