点击按钮弹出可自定义小弹框即实现模态窗口
最近做项目要实现一个功能,当点击新建项目按钮时,弹出一个弹框,要填写项目名称,创建团队,然后提交,当弹框出现时,背景暗,且点击无效。
对这个功能,我先想到的就是像alert()或window.open()方法,但是这些方法都不能实现这个功能,所以我用了两个div来实现。一个大div为div_black,作为背景div,还有一个是div_iterm,用来实现弹框的内容
<div class="div_black" id="div_black"></div>
<div class="div_iterm" id="div_iterm">
<label>项目名称</label>
<input class="iterm_name"/><br/>
<label>团队名称</label>
<input class="team_name"/><br/>
<button class="btn" id="submit_btn">submit</button>
<button class="btn" id="close_btn">close</button>
</div>
<button id="creat_iterm">creat</button>
接下来是定义这两个div的样式了,这个是实现弹窗效果的关键,要设置为绝对定位,然后设置z-index让弹框在上面。
.div_black{
display:none;
width:100%;
height:100%;
position:absolute;
top:0;
left:0;
z-index:1000;
background:rgba(0,0,0,0.6);
}
.div_iterm{
display:none;
width:50%;
position:absolute;
top:150px;
left:25%;
z-index:1001;
}
然后是给按钮绑定事件,首先是点击creat按钮弹出弹框,然后填写完成后,点击提交按钮或关闭按钮收起弹框,注意收起弹框后要清除表单中填写内容,这里考虑到如果填写内容比较多,那么可以用each()函数遍历每一个input设置内容为空。
$('#creat_iterm').bind('click',function(){
$('#div_black').css('display','block');
$('#div_iterm').css('display','block');
$('#div_iterm input").each(function(){
$(this).val("");
});
});
$('#submit_btn').bind('click',function(){
$('#div_black').css('display','none');
$('#div_iterm').css('display','none');
});
以上是我实现弹窗的方法,也有很多实现模态弹窗的插件。如果哪位大神有更好的方法,请指教!