居中div

作者: 我竟无言以对_1202 | 来源:发表于2017-12-14 15:42 被阅读0次
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            height: 2000px;
        }
        #box{
            width: 400px;
            height: 400px;
            border: 1px solid #000;
            position: absolute;
        }

    </style>
</head>
<body>
    <div id="box">
    </div>
</body>
<script>
    function views(){
        return {
            w: document.documentElement.clientWidth,
            h: document.documentElement.clientHeight
        }
    }
    function scroll(){
        return {
            t: document.documentElement.scrollTop,
            l: document.documentElement.scrollLeft
        }
    }
    var box = document.getElementById("box");
    function changeLT(){
        box.style.left = (views().w - box.offsetWidth)/2 + 'px';
        box.style.top = (views().h - box.offsetHeight)/2 + 'px';
    }
    changeLT();

    window.onscroll = function(){
        console.log(scroll().l);
        console.log(scroll().t);
        box.style.left = (views().w - box.offsetWidth)/2 +scroll().l+ 'px';
        box.style.top = (views().h - box.offsetHeight)/2 +scroll().t+ 'px';
    }

    window.onresize = function(){
        changeLT();
    }
</script>
</html>

相关文章

网友评论

      本文标题:居中div

      本文链接:https://www.haomeiwen.com/subject/lwukwxtx.html