描述: 用JS动态实现盒子水平垂直居中(考虑scroll和resize的情况)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
width: 2000px;
height: 2000px;
}
div {
position: absolute;
width: 200px;
height: 200px;
border: 1px solid #000;
display: none;
}
span {
position: absolute;
right: 10px;
top: 10px;
}
</style>
</head>
<body>
<button>显示</button>
<div>
<span>X</span>
</div>
<script>
var btn = document.querySelector('button');
var div = document.querySelector('div');
console.log(btn, div);
btn.onclick = function () {
div.style.display = 'block';
div.style.left = document.documentElement.clientWidth / 2 - div.offsetWidth / 2 + 'px';
div.style.top = document.documentElement.clientHeight / 2 - div.offsetHeight / 2 + 'px';
}
window.onscroll = function () {
var st = document.documentElement.scrollTop;
var sl = document.documentElement.scrollLeft;
div.style.left = document.documentElement.clientWidth / 2 - div.offsetWidth / 2 + sl + 'px';
div.style.top = document.documentElement.clientHeight / 2 - div.offsetHeight / 2 + st + 'px';
}
window.onresize = function(){
div.style.left = document.documentElement.clientWidth / 2 - div.offsetWidth / 2 + 'px';
div.style.top = document.documentElement.clientHeight / 2 - div.offsetHeight / 2 + 'px';
}
var span = document.querySelector('span');
span.onclick = function(){
div.style.display = 'none';
}
</script>
</body>
</html>