日期:2014-05-17  浏览次数:20652 次

怎么让一个div在网页可视范围垂直居中
我试过让这个div
这个函数  

  var h=window.screen.height;
var w=window.screen.width;
function hw(){
  document.getElementById("jingdu").style.left=w/2;
  document.getElementById("jingdu").style.top=h/2;
}
但是这样 当网页高度很大的时候 div 就跑到上面去了
  我就是想让这个div在网页可视范围垂直居中

------解决方案--------------------
直接在CSS中把div的属性设置为margin:0px auto
不行就设置为margin-left:(1000-div的宽度)/2
------解决方案--------------------
你是一定想用js函数实现?

如果不是,直接写div的css的话可以这样写
div 
{
position:absolute;
width:200px;
height:200px;
left:50%;
top:50%;
margin:-100px 0 0 -100px;
}

这样div就是绝对上下左右都居中了,
js无非就是把这些属性写到函数里 去

试试吧
------解决方案--------------------
To:GAVIN_JAVA ,pears2017ms 如果div的高度和宽度不固定 恐怕你的招数也不行了;

参考下面代码:

/// <summary>
/// 获取屏幕高宽。
/// </summary>
/// <author>Mike Cheers</author>
/// <date>2006-10-27</date>
function getScreenArea()
{
this.clientWidth = 0;
this.clientHeight = 0;
this.scrollLeft = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
this.scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
this.scrollWidth = (document.documentElement.scrollWidth ? document.documentElement.scrollWidth : document.body.scrollWidth);
this.scrollHeight = (document.documentElement.scrollHeight ? document.documentElement.scrollHeight : document.body.scrollHeight);

if (window.innerWidth) {
this.clientWidth = (window.__safari ? window.innerWidth : Math.min(window.innerWidth, document.documentElement.clientWidth));
} else {
this.clientWidth = document.documentElement.clientWidth;
}

if (window.innerHeight) {
this.clientHeight = (window.__safari ? window.innerHeight : Math.min(window.innerHeight, document.documentElement.clientHeight));
} else {
this.clientHeight = document.documentElement.clientHeight;
}
}
/// <summary>
/// 加载loadBgLayer层。
/// </summary>
/// <author>Mike Cheers</author>
/// <date>2006-11-6</date>
function loadingLayout()
{
var ca = new getScreenArea();
var bgDiv = GE("loadBgLayer");
if(bgDiv != null){
bgDiv.style.left = ca.scrollLeft+((ca.clientWidth-bgDiv.offsetWidth)/2) + 'px';
bgDiv.style.top = ca.scrollTop+((ca.clientHeight-bgDiv.offsetHeight)/2) + 'px';
}
}