首页 > 编程 > JavaScript > 正文

js实现类bootstrap模态框动画

2019-11-19 17:41:55
字体:
来源:转载
供稿:网友

在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";});

是不是看起来很容易,运行之后,诶?并没有我们所希望看到的动画效果,这是为什么呢?当我们点击按钮的时候不是已经把动画加上了么?

其实仔细想想,点击按钮改变classname的时候,是一下子把元素display和动画属性全都加上了,当模态框显示出来的时候动画也随着完成了,就类似于打开一个html页面一样,页面元素的css属性都在页面渲染的时候发挥了作用。而我们在页面直接去触发一个已经显示出来的元素动画的时候是有效的。所以我们需要把元素显示和动画分开来做。

这里我做了一个异步操作(setTimeout)。

  oModal.style.display = "block";  var timer = setTimeout(function(){    oModal.className = "modal in";    clearTimeout(timer);  },0);

元素显示出来之后在给它加动画效果,这样就可以实现我们所期望的动画效果了。
所有代码在github上https://github.com/Stevenzwzhai/plugs/tree/master/dialog,在这个项目下有多个js的常用插件,欢迎点赞。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表