弹出层居中


相关知识点:

滚动距离:scrollTop/scrollLeft

document.documentElement.scrollTop||document.body.scrollTop   后者为处理google兼容

可视区大小:clientWidth/clientHeight
document.documentElement.clientHeight

物体大小、位置:offsetLeft/offsetTop/offsetHeight/offsetWidth


<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style type="text/css">
body{ height:3000px; }
#div1{ position:absolute; left:50%; width:300px; height:200px; background:red; margin-left:-150px;}
</style>
<script type="text/javascript">
window.onload=window.onscroll=window.onresize=function ()
{
    var oDiv=document.getElementById('div1');
    var scrollTop=document.documentElement.scrollTop|| document.body.scrollTop;  //后者为兼容google
    oDiv.style.top=scrollTop+(document.documentElement.clientHeight-oDiv.offsetHeight)/2+"px";
};

</script>
</head>

<body>
<div id="div1"></div>
</body>
</html>
Hello Javascript!
原文地址:https://www.cnblogs.com/chenyajie/p/2937093.html