<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="btn" style="margin-top:1000px;">btn</div> <div id="box" style="display:none;position:absolute;100px;height:100px;background:#f00"></div> <script type="text/javascript"> function scrollX () { var de = document.documentElement; return self.pageXOffset || (de && de.scrollLeft) || document.body.scrollLeft; } function scrollY () { var de = document.documentElement; return self.pageYOffset || (de && de.scrollTop) || document.body.scrollTop; } function windowHeight () { var de = document.documentElement; return self.innerHeight || (de && de.clientHeight) || document.body.clientHeight; } function windowWidth () { var de = document.documentElement; return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth; } function setPos () { var t = (windowHeight() - 100)/2 + scrollY(), l = (windowWidth() - 100)/2 + scrollX(); document.getElementById('box').style.top = t + 'px'; document.getElementById('box').style.left = l + 'px'; document.getElementById('box').style.display = 'block'; } document.getElementById('btn').onclick = function () { setPos(); }; window.onresize = function(){ setPos(); } </script> </body> </html>
by 《精通JavaScript》