博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

网页元素垂直居中 css 方法和Js方法

Posted on 2011-06-05 15:30  李望生  阅读(1007)  评论(0)    收藏  举报

垂直居中的方法:
css:

#div{

position:absolute;
height:x;
width:y;
top:50%;
left:50%;
margin-top:x/2;
margin-left:y/2;

}
这种方法只是在可视的区域是居中的,就是说在没有滚动条时候还可以,当出现滚动条页面拉长或拉宽就不管用了


js 垂直居中方法:
css:
#div
{
position:absolute;

}


js :

  document.getElementByIdx ("loading").style.top=document.documentElement.clientHeight/2-#div.height;
  document.getElementByIdx ("loading").style.left=document.documentElement.clientWidth/2-#div.width;
如果这样效果同上面完全的css方法是一样的,就是在可视区域内居中。

如果按照下面的这样写的话就会在整个页面的居中:

  document.getElementByIdx ("loading").style.top=document.documentElement.scrollHeight/2-#div.height;
  document.getElementByIdx ("loading").style.left=document.documentElement.scrollWidth/2-#div.width;


window事件执行的两种方式:
function  aa(){

....
}

window.onresize=aa();

window.attachEvent("onresize",aa());

attachEvent()方法的两个参数:第一个是事件的名称,第二个是要执行的函数名。

通过attachEvent方法可以实现在一个事件中执行多个函数。具体是这样的:

window.attachEvent("onresize",aa());
window.attachEvent("onresize",aa1());
window.attachEvent("onresize",aa2());