自写简单弹出框

今天下午没事,就想起自己要写个弹出框试试。首先在网上搜了哈加上了自己的一些想法,结果达到了自己预想的结果。

实现原理:

1、在页面中创建一个div。

2、将此div的position设置为absolute,并设置其left、top、width、height属性。

3、设置此div的z-index为一个较大值,以保证覆盖弹出层底下的元素。

4、通过div的显示和隐藏达到弹出效果。

直接上代码吧!为了大家方便测试,我已经将js和css都放在html中了。

注意:需要自己引入jquery.min.js

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>弹出层Demo</title>
    <script src="/js/jquery-1.6.2.min.js" type="text/javascript"></script>
    <style>
.backgroundOverlay{
    display: none;
    position: absolute;
    top: 0%;
    left: 0%;
    100%;
    height: 100%;
    background-color:black;
    z-index:1001;
    -moz-opacity: 0.8;
    opacity:.80;
    filter: alpha(opacity=80);
}
.white_content {
    display: none;
    position: absolute;
    top: 10%;
    left: 10%;
    80%;
    height: 80%;
    border: 2px solid lightblue;
    background-color: white;
    z-index:1002;
    overflow: auto;
}

.white_content_small {
    display: none;
    position: absolute;
    top: 20%;
    left: 30%;
    40%;
    height: 50%;
    border: 2px solid lightblue;
    background-color: white;
    z-index:1002;
    overflow: auto;
}

.formdemo{ text-align:center;}
.formdemo input{ margin-top:20px;}

</style>
 <script type="text/javascript">
    //弹出隐藏层
function ShowDiv(show_div,bg_div){
   document.getElementById(show_div).style.display='block';
   document.getElementById(bg_div).style.display='block' ;
   var bgdiv = document.getElementById(bg_div);
   bgdiv.style.width = document.body.scrollWidth;
  // bgdiv.style.height = $(document).height();
   $("#"+bg_div).height($(document).height());
};
//关闭弹出层
function CloseDiv(show_div,bg_div)
{
    document.getElementById(show_div).style.display='none';
    document.getElementById(bg_div).style.display='none';
};
</script>
    
</head>
<body>
<input id="Button1" type="button" value="修改用户" onclick="ShowDiv('MyDiv','fade')" />
<!--弹出层时背景层DIV-->
    <div id="fade" class="backgroundOverlay">
    </div>
    <!-- 弹出层DIV-->
    <div id="MyDiv" class="white_content_small">
        <div style="text-align: right; cursor: default; height: 40px;">
            <span style="font-size: 16px;" onclick="CloseDiv('MyDiv','fade')">关闭</span>
        </div>
           <form action="#" method="post" id="myForm" class="formdemo">
                输入用户<input type="text" /><br/>
                再次输入<input type="text"/> <br/>
                <input type="submit" value="确定" />
                <input type="reset" value="重置"  />
          </form>        
                
    </div>
</body>
</html>

希望自己的积累能给其他人带来帮助,爱代码,爱生活!

原文地址:https://www.cnblogs.com/xubiao/p/4213848.html