日期:2014-05-16  浏览次数:20360 次

谁能将下面代码做最小改动,实现将三个span居中放置在一个div中
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=GBK"/>
  <title>span居中</title>

</head>
<body>
<div id="div1" style="width: 500px;height: 100px;border: solid black;position: relative;">
  <span id="span1" style="position: relative;">1</span>
  <span id="span2" style="position: relative;">2</span>
  <span id="span3" style="position: relative;">3</span>
</div>
<script type="text/javascript">
  var sp=[span1,span2,span3];
  var i=1;
  for(spa in sp)
  {
  spa=document.getElementById('span'+i);
  i++;
  }
  var div1=document.getElementById('div1');
  var len=0;
  for(spa in sp)
  {
  len+=parseInt(spa.offsetWidth);
  }
  span1.style.marginLeft=(div1.offsetWidth-len)/2+'px';
</script>

</body>
</html>

------解决方案--------------------
<div id="div1" align="center" style="width: 500px;height: 100px;border: solid black;position: relative;">
<span id="span1" style="float:center ;position: relative;display:block;">1</span>
<span id="span2" style="float:center ;position: relative;display:block;">2</span>
<span id="span3" style="float:center ;position: relative;display:block;">3</span>
</div>
------解决方案--------------------
不改html还可以,至于js我不得不全改了:
JScript code
<script type="text/javascript">
  var sp=["span1","span2","span3"];
  for(var i in sp)
  {
    var spa=document.getElementById(sp[i]);
    spa.style.position="absolute";
    spa.style.top=40;
    spa.style.left=250+i*10;
  }
</script>