首页 > 语言 > JavaScript > 正文

js实现类bootstrap模态框动画

2024-05-06 15:01:34
字体:
来源:转载
供稿:网友

在pc端开发,模态框是一个很常用的插件,之前一直用的第三方插件,比如bootstrap,jQuery的模态框插件,最近还用了elementUI的。但是会发现其实动画效果都差不多,那么如何去实现这样一个动画效果呢?

模态框的构成

 常见的模态框的结构我们很容易就可以看出,一个遮罩层,还有内容区。内容区主要是头部(包括标题,关闭按钮)和body部分(body中常常会有确认和取消按钮)。

布局

 1.背景要充满全屏,而且如果页面有滚动,当模态框弹出的时候是无法滚动的;
 2.内容区要水平居中显示,至于垂直方向看设计喽;
 3.模态框出现是渐渐显示出来,而且从顶部滑下;

实现

 遮罩使用最外层元素占满全屏(position:fixed;),并设置背景色不透明度(rgba(0,0,0,0.5))。
 水平居中有很多方式,这里使用

margin:30px auto;

重点介绍下关于模态框动画的实现

 关于渐渐显示使用opacity就可以,而从顶部滑下使用translate也很容易实现。这么看来,很容易做嘛,只需要改变classname就可以了。
html

<input type="button" value="click" id="btn"><div class="modal" id="modal">  <div class="dialog">    <header class="dialog-header">      <h3>this is dialog title</h3>      <span id="close">×</span>    </header>    <div class="dialog-content">      this is dialog content     </div>   </div></div>

style

.modal{    position:fixed;    left:0;    right:0;    top:0;    bottom:0;    background-color:rgba(0,0,0,0.5);    display:none;    z-index:1050;    opacity:0;    transition: all .5s ease-out 0s;  }  .dialog{    width:500px;    height:300px;    position:relative;    box-shadow:0 5px 15px rgba(0,0,0,.5);    border-radius:10px;    background-color:#fff;    margin:30px auto;    transform: translate(0,-40%);    -webkit-transform: translate(0,-40%);    transition: all .5s ease-out 0s;  }  .dialog-header{    box-sizing:border-box;    border-bottom:1px solid #ccc;  }  .dialog-header h3,.dialog-header span{    display:inline-block;  }  .dialog-header span{    float:right;    margin-right:10px;    overflow: hidden;    line-height:58px;    cursor:default;    font-size:18px;  }  .in{    opacity: 1;  }  .in .dialog{    transform: translate(0,0);    -webkit-transform: translate(0,0);  }

js

var oBtn = document.getElementById("btn");var oModal = document.getElementById("modal");var oClose = document.getElementById("close");oBtn.addEventListener("click", function(){  oModal.style.display = "block";  oModal.className = "modal in";});oClose.addEventListener("click", function(){  oModal.style.display = "none";  oModal.className = "modal";});            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选