使层的位置始终显示在页面的正中央。

<!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>无标题页</title>
</head>
<body>
<div style="width:2000px;height:2000px;"></div>
<div id="div" style="position:absolute; background-color:Green; width:100px; height:100px;"></div>
</body>
</html>
<script type="text/javascript">
    function $(id){return document.getElementById(id);};
    var div = $("div");
   
    function reset()
    {
        var d = document.documentElement;
        //  首先取得页面现在的左上角相对位置
        var x1 = d.scrollLeft;
        var y1 = d.scrollTop;
        var w1 = d.clientWidth;
        var h1 = d.clientHeight;
       
        //  取得浮动层的信息
        var w = parseInt(div.style.width);
        var h = parseInt(div.style.height);
        var x = Math.ceil((w1 - w)/2) + x1;
        var y = Math.ceil((h1 - h)/2) + y1;
       
        //  设置位置
        div.style.left = x;
        div.style.top = y;
    }
    window.onresize = reset;
    window.onscroll = reset;
    reset();
</script>
 

你可能感兴趣的:(html,function,XHTML,div)