用js来定义浏览器中一个左右浮动元素相对于页面主体宽度的位置的函数

  首先这个元素position为fixed

  top为(clientHeight-elem.offsetHeight)/2(即元素在浏览器的中间,这个是固定的)

  left为(clientWidht-主体宽度)/2+主体宽度+左边距,左边距可以设为正数,也可以为负数,如果为负数时的绝对值 等于 主体宽度+elem.offsetWidht,那么元素就刚好浮动在页面主体的左边,设置为0时,刚好浮动在页面主体的右边

  但是万恶的ie6不支持css中fixed属性,好在ie6可以通过expresion表达式来解决,万事大吉

  具体看代码:

  

复制代码 代码如下:

  <!DOCTYPE html>

  <html>

  <head>

  <meta charset="gb2312" />

  <title>左右浮动元素</title>

  <style type="text/css">

  html{_background-image:url(about:blank);_background-attachment:fixed;/*针对ie6,解决窗口滚动时的抖动*/}

  body{margin:0;padding:0;}

  .box-wrap{width:990px;margin:0 auto;height:5000px;background:#999;}

  .pos-id{width:50px;height:200px;line-height:200px;background:#F00;

  /*针对ie6*/

  _position:absolute;

  _bottom:auto;

  _top:expression(eval(document.documentElement.scrollTop+(document.documentElement.clientHeight-this.offsetHeight)/2-

  (parseInt(this.currentStyle.marginTop)||0)-(parseInt(this.currentStyle.marginBottom)||0)));

  /*其中的_top为浏览器的垂直居中线上,left在js定义中*/

  }

  .pos-id a{color:#FFF;font-size:12px;}

  </style>

  </head>

  <body>

  <div class="box-wrap" id="box-wrap">

  <div class="pos-id" id="pos-id">

  <a href="http://www.glzy8.com/" title="管理资源吧" target="_blank">管理资源吧</a>

  </div>

  </div>

  <script language="javascript">

  window.onload = function(){

  /*

  ----------------------------------

  定义一个浏览器左右浮动元素相对于页面主体宽度的位置的函数

  ----------------------------------

  */

  function setScrollDivPos(elemId_str,main_width,m_left){

  //自定义一个获取元素的函数

  $ = function(id){return document.getElementById(id);};

  //获取浏览器在标准模式和混杂模式的视口大小

  var c_width = document.documentElement.clientWidth || document.body.clientWidth;

  var c_height = document.documentElement.clientHeight || document.body.clientHeight;

  //获取浏览器滚动时顶部被隐藏的像素大小

  //var s_top = document.documentElement.scrollTop || document.body.scrollTop;

  //获取浏览器视口宽度减去页面主题宽度的一半

  var half_width = (c_width - main_width)/2;

  //获取浏览器视口高度的一半

  var half_height = c_height/2;

  //获取元素的高度

  var elem_height = $(elemId_str).offsetHeight;

  //获取元素相对于页面主体的(左、上)相对位置

  var pos_left = main_width + half_width + m_left + "px";

  var pos_top = (c_height - elem_height)/2 + "px";

  //获取浏览器顶部的滚动大小

  //var s_top = document.documentElement.scrollTop || document.body.scrollTop;

  //对元素进行定位布局

  if(window.XMLHttpRequest){

  $(elemId_str).style.cssText = 'position:fixed;top:' + pos_top + ';left:' + pos_left + ';';

  }else{

  $(elemId_str).style.cssText = ';left:' + pos_left + ';';

  }

  }

  //定义id为pos-id的元素 在页面主题宽度为990px的左侧

  //setScrollDivPos("pos-id",990,-1040);

  //定义id为pos-id的元素 在页面主题宽度为990px的右侧

  setScrollDivPos("pos-id",990,0);

  }

  </script>

  </body>

  </html>