弹出层水平垂直居中(支持浏览器窗口大小改变,存在垂直滚动条)
<!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>
运行效果