<!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>
网友评论