jQuery写简单模态框

来源:互联网 发布:linux网卡配置生效 编辑:程序博客网 时间:2024/06/06 01:56

css代码

<style type="text/css">
            body,div,a,p,span{
                margin: 0;
                padding:0;
            }
            .shade{
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,.5);
                position: absolute;
                z-index: 1;
                display: none;
            }
            .login{
                padding:10px;
                border-radius: 10px;
                width:300px;
                height: 200px;
                background: #fff;
                position: absolute;
                z-index: 2;
                display: none;
            }
            span{
                float: right;
                cursor: pointer;
            }
            .title{
                border-bottom: 1px #ccc solid;
                text-align: center;
                font-weight: bold;
                padding:5px 0 10px 0;
            }
        </style>

html代码

<div class="shade"></div>
        <div class="login">
            <p class="title">弹出标题<span>&times;</span></p>
            <p class="cont">弹出内容</p>
        </div>
        <a href="#">登录</a>

script 代码

<script type="text/javascript">
        $(function(){
            //浏览器大小发生改变
            $(window).resize(function(){
                showShade();
            });

            //模态框出现
            $("a").bind("click",function(){
                $(".shade").fadeIn(1000);
                $(".login").fadeIn(1000);
                $(this).css("display","none");
                showShade();
            });
            //点击span关闭
            $("span").bind("click",function(){
                $(".shade").fadeOut(1000);
                $(".login").fadeOut(1000);
            });
            
            //居中显示
            function showShade(){
                var $vW = $(window).width();
                var $w = $(".login").outerWidth();
                var $vH = $(window).height();
                var $h = $(".login").outerHeight();
                $(".login").css({"left":($vW - $w)/2 + "px","top":($vH - $h)/2 + "px"});
            };
            
            //绑定键盘事件  按下esc键退出
            $(document).keyup(function(ev){
//                alert(ev.keyCode);  获取esc的键码27
                if(ev.keyCode == 27){
//                    $("span").click();
                    //模拟事件
                    $("span").trigger("click");
                }
            })
            
        })
    </script>