码迷,mamicode.com
首页 > 其他好文 > 详细

弹出层水平垂直居中(支持浏览器窗口大小改变,存在垂直滚动条)

时间:2015-01-21 01:10:14      阅读:640      评论:0      收藏:0      [点我收藏+]

标签:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>弹出层水平垂直居中</title>
    <script src="jquery-1.7.2.js" type="text/javascript"></script>
    <script language="javascript">
        //水平垂直居中 支持浏览器窗口大小改变,存在垂直滚动条
        function center(obj) {
            var screenWidth = $(window).width(), screenHeight = $(window).height();  //当前浏览器窗口的宽高
            var scrolltop = $(document).scrollTop();//获取当前窗口距离页面顶部高度
            var objLeft = (screenWidth - obj.width()) / 2;
            var objTop = (screenHeight - obj.height()) / 2 + scrolltop;
            obj.css({left: objLeft + px, top: objTop + px});
            //浏览器窗口大小改变时
            $(window).resize(function () {
                screenWidth = $(window).width();
                screenHeight = $(window).height();
                scrolltop = $(document).scrollTop();
                objLeft = (screenWidth - obj.width()) / 2;
                objTop = (screenHeight - obj.height()) / 2 + scrolltop;
                obj.css({left: objLeft + px, top: objTop + px});
            });
            //浏览器有滚动条时
            $(window).scroll(function () {
                screenWidth = $(window).width();
                screenHeight = $(window).height();
                scrolltop = $(document).scrollTop();
                objLeft = (screenWidth - obj.width()) / 2;
                objTop = (screenHeight - obj.height()) / 2 + scrolltop;
                obj.css({left: objLeft + px, top: objTop + px});
            });
        }
        $(function () {
            $("#button").click(function () {
                center($("#tcc"));
                $("#tcc").show();
            });
            $("#tcc").click(function () {
                $(this).hide();
            });

        });
    </script>
</head>
<body style="height: 2000px;">
<div id="button" style="width: 100px;height: 500px; margin-top: 300px;">点击弹出层</div>
<div id="tcc" style="display: none;position: absolute; width: 500px;height: 500px; background-color: red;">
    弹出层(position: absolute; 必须)
</div>
</body>
</html>

 

运行效果

技术分享

弹出层水平垂直居中(支持浏览器窗口大小改变,存在垂直滚动条)

标签:

原文地址:http://www.cnblogs.com/lion88/p/4237797.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!