scroll和offset实现元素居中
2019-05-22 09:58
169 查看
元素居中
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"; } }
效果图
相关文章推荐
- absolute元素实现居中方式
- 完美实现浮动元素横排居中显示
- 三种方式实现动态元素水平居中
- 用 CSS 和 JS 实现元素的水平垂直居中
- 六种实现元素水平居中
- css实现高度不固定的div元素模块在页面中水平垂直居中
- margin:0 auto与body{text-align:center;}实现元素居中的区别
- 利用writing-mode实现元素的垂直居中
- 页面元素坐标和偏移(clientX/pageX/screenX/layerX/offsetWidth/scrollWidth/clientWidth等)相关整理
- flex实现元素左右居中+垂直居中
- css实现元素居中
- 用CSS实现任何元素的垂直居中
- CSS实现定位元素居中的方法
- CSS3 Flexbox轻巧实现元素的水平居中和垂直居中
- css中实现元素的绝对居中
- 小tip: margin:auto实现绝对定位元素的水平垂直居中
- CSS 实现:元素相对于文档水平垂直居中
- 未知宽高元素实现页面水平居中
- DIV六种实现元素水平居中
- 子元素scroll父元素容器不跟随滚动(JS实现),子元素内滚动条没有(css实现)