菜鸟新手,初入前端,初来csdn,请各位大神多多指教。
这是关于JS定位浏览器窗口的代码。
代码中结构样式和JS写在一起。
图片版和文字版如下:
<style type="text/css">
#div{ width:100px; height:100px; background: red; position: absolute; }
</style>
<script type="text/javascript">
//用JS定位一个据浏览器窗口左右上下都居中
window.onload = function(){
var oDiv = document.getElementById("div");
var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
var offsetX = (clientWidth - oDiv.offsetWidth) / 2;
var offsetY = (clientHeight - oDiv.offsetHeight) / 2;
oDiv.style.left = offsetX + "px";
oDiv.style.top = offsetY + "px";
document.onscroll = function(){
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
oDiv.style.top = offsetY + scrollTop + "px";
}
}
</script>