Javascript 连连看

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>连连看</title>
 <style type="text/css">
  #main{
   width:550px;height:300px;
   border:1px solid blue;
   overflow:hidden;zoom:1;
  }
  #main div{
   width:50px;height:50px;
   background-color:#F5E488;
   float:left;
   margin:5px;
  }
 </style>
 <script type="text/javascript">
  //最大的div对象
  var main;
  //小的
  var boxs=[];
  //当前被点中的对象
  var currentBox=null;
  
  //初始化函数
  function init(){
   
   main=document.getElementById("main");
   
   //alert(333);
   for(var i=0;i<20;i++){
    //创建对象
    createBox(i);
   }
   
   //将数组中的box,放到main中
   show();
   
  }
  
  //页面加载完成后,调用init方法
  window.onload=init;
  
  //创建div
  function createBox(num){
   var obj=document.createElement("div");
   obj.innerHTML=num;   
   //添加事件
   obj.onclick=play;
   boxs[boxs.length]=obj;
   
   //再来一个
   obj=document.createElement("div");
   obj.innerHTML=num;
   //添加事件
   obj.onclick=play;
   boxs[boxs.length]=obj;
   
  }
  
  //显示
  function show(){
   for(var i in boxs){
    main.appendChild(boxs[i]);
   }
  }
  
  //玩游戏
  function play(e){
   //取被点中的对象
   //IE兼容处理
   e= e || window.event;
   //此时目标对象
   e.target = e.target || e.srcElement;
   
   if(currentBox!=null){
    check(e.target);
    return;
   }
   
   currentBox=e.target;
   //alert(currentBox);
   currentBox.style.backgroundColor="green";
   
  }
  
  //判断是否已经选中一对象
  function check(obj){
   
   if(obj===currentBox){
    return;
   }
   
   if(currentBox.innerHTML==obj.innerHTML){
    currentBox.style.visibility="hidden";
    obj.style.visibility="hidden";

     currentBox=null;


   }else{
    //如果不等,则取消选中状态
    currentBox.style.backgroundColor="#F5E488";
    currentBox=null;
   }
  }
 </script>
</head>
<body>
 
 <div id="main"></div>
 
</body>
</html>

posted @ 2013-06-05 20:12  午时的海  阅读(167)  评论(0编辑  收藏  举报