scroll和offset实现元素居中

博客围绕元素居中展开,提及使用scroll和offset实现元素居中,并展示了效果图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

元素居中

html
<body style="height: 2000px;">
    <button>显示</button>
    <div><button>X</button></div>
css
 div{width: 200px;height: 200px;border: 2px solid red;position: absolute;display: none;}
        div button{float: right;}
script
 window.onload = function () {
            //1.获取元素
            var oBut = document.getElementsByTagName("button");
            var oDiv = document.getElementsByTagName("div")[0];

            //2.点击显示按钮,显示div,并且div居中
            oBut[0].onclick = function () {
                oDiv.style.display = "block";
                //(屏幕的可视化宽度  -  当前div的真实占位宽度)/2
                oDiv.style.left = document.documentElement.clientWidth/2-oDiv.offsetWidth/2+"px";
                
                oDiv.style.top = document.documentElement.clientHeight/2-oDiv.offsetHeight/2+"px";
            }

              //3.点击关闭按钮,隐藏div
            oBut[1].onclick = function () {
                oDiv.style.display = "none";
            }
            
            //4.滚动的时候,设置div居中
            window.onscroll = function () {
                //获取被卷去的高(滚动距离)
                var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                //获取屏幕的宽度
               var clientWidth = document.documentElement.clientWidth;
                oDiv.style.left = clientWidth/2-oDiv.offsetWidth/2+"px";
                oDiv.style.top = document.documentElement.clientHeight/2-oDiv.offsetHeight/2+scrollTop+"px";
            }
            //5.改变窗口
            //窗口的宽高发生了变化  就会来去执行这个方法
            window.onresize = function () {
            	console.log('窗口发生了改变')
                var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                oDiv.style.left = document.documentElement.clientWidth/2-oDiv.offsetWidth/2+"px";
                oDiv.style.top = document.documentElement.clientHeight/2-oDiv.offsetHeight/2+scrollTop+"px";
            }

        }

效果图
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值