1、让元素在屏幕中央显示的 jQuery 函数
 
  
  1. 以下代码可让元素在屏幕中央显示,无论网页是否滚动。  
  2.  
  3. jQuery.fn.center = function () {  
  4.  $win = $(window);  
  5.  this.css('position','absolute');  
  6.  this.css('top', (($win.height() - this.outerHeight()) / 2) + $win.scrollTop() + 'px');  
  7.  this.css('left', (($win.width() - this.outerWidth()) / 2) + $win.scrollLeft() + 'px');  
  8.  return this;  
  9. }  
  10.  
  11. 用法举例如下:  
  12.  
  13. HTML代码:  
  14.  
  15. <img id="test" src="http://www.google.co.jp/p_w_picpaths/nav_logo83.png" />  
  16. JS 代码:  
  17.  
  18. window.onscroll = $('#test').center();  
  19. window.onresize = $('#test').center();  
  20. window.onload = $('#test').center(); 

2、css控制

 
  
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">   
  2. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />   
  3. <style type="text/css">   
  4. <!--   
  5. div {   
  6. position:absolute; //绝对定位   
  7. top:50%; //距顶部50%   
  8. left:50%;   
  9. margin:-100px 0 0 -200px; //设定这个div的margin-top的负值为自身的高度的一半,margin-left的值也是自身的宽度的一半的负值.(感觉在绕口令)   
  10. width:400px; //宽为400,那么margin-top为-200px   
  11. height:200px; //高为200那么margin-left为-100px;   
  12. border:1px solid red;   
  13. line-height:200px;   
  14. font-size:16px;   
  15. text-align:center;   
  16. z-index:99; //浮动在最上层   
  17. }   
  18. -->   
  19. </style>