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

一段小代码,ie6下无法运行
一段小代码,ie6下无法运行,opera、firefox 下可以运行。
请教如何在ie6下运行。

<html>
  <body>
    <table    align="center"  valign=middle  border="0" > 
      <tr  height=48px >
         <td  width=48px bgcolor="green" id="a1" > </td>
         <td  width=48px bgcolor="green" id="a2" > </td>
      </tr>      
    </table>
    <input type="button" value="change"  id="cc" onclick="cc()"> 
</body>
<script>
function cc()
{
  var color=new Array("white","blue","green","orange","red");
  document.getElementById("a1").style.backgroundColor=color.splice(parseInt(Math.random()*6-1),1)
  document.getElementById("a2").style.backgroundColor=color.splice(parseInt(Math.random()*5-1),1)
}
</script>
</html>




------解决方案--------------------
.style.backgroundColor要求是字符串
但splice函数的返回值是个数组,不是字符串
function cc()
{
  var color=new Array("white","blue","green","orange","red");
  document.getElementById("a1").style.backgroundColor=color.splice(Math.floor(Math.random()*color.length),1)[0];
  document.getElementById("a2").style.backgroundColor=color.splice(Math.floor(Math.random()*color.length),1)[0];
}

------解决方案--------------------
偷个懒,保证每次的两种不同,但不排除与上一批次的相同,需要的话,自己加上些逻辑去判断吧
function cc(){  
  var color=["pink","blue","green","orange","red"].sort(function(){return 0.5 - Math.random()}); 
  color.length=2;
  document.getElementById("a1").style.backgroundColor=color[0]; 
  document.getElementById("a2").style.backgroundColor=color[1]; 
}