scroll和offset实现元素居中

    xiaoxiao2022-07-02  106

    元素居中

    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"; } }

    效果图

    最新回复(0)