zoukankan      html  css  js  c++  java
  • javascript --关灯游戏

    分析:

    搭建10 * 10 的小方块

    <script type="text/javascript" >

      var body = document.getElementsByTagName('body')[0]; //返回数组[0]

      var wrap = document.createElement('div');

      wrap.style.width = '500px';

      wrap.style.height = '500px';

      wrap.style.border = '1px solid gray';

      wrap.style.margin = '0 auto';

      wrap.style.position = 'relative';

      var arr = []; //用于存放每个div小方格

      for(var i = 0; i < 10; i++) {

        for( var j = 0; j < 10; j++) {

          var light = document.createElement('div');  //创建小方格

          light.style.width = '50px';

          light.style.height = '50px';

          light.style.background = 'black';

          light.style.border = '1px solid gray';

          light.style.position = 'absolute';

          light.style.left = i * 10 + '%';

          light.style.top = j * 10 + '%';

          light.index = arr.length;

          arr.push(light);//  将div 添加到数组中

          light.onclick = function() {    //添加点击事件

            var currentLight = event.target;    //获取当前的灯

            if(currentLight.style.background == 'black') {

              currentLight.style.background = 'blue';

            } else {

              currentLight.style.background = 'black';

            }

            if (currentLight.index >= 10) {

              var top = arr[currentLight.index - 10];

              top.style.background = (top.style.background == 'black') ? 'blue' : 'black';

            }

            if (currentLight.index + 10 < arr.length) {

              var bottom = arr[currentLight.index + 10];

              bottom.style.background = (bottom.style.background == 'black') ? 'blue' : 'black';

            }

            if(currentLight.index % 10 != 0 ){

              var left = arr[currentLight.index - 1];

              left.style.background = (left.style.background== 'black') ? 'blue' : 'black';

            }

            if(currentLight.index % 10 < 9) {

              var right = arr[currentLight.index + 1];

              right.style.background = (right.style.background == 'black') ? 'blue' : 'black';

            }

          }

          wrap.appendChild(light); 

        }  

      }

      body.appendChild(wrap); 

    </script>

  • 相关阅读:
    记一次CTF比赛过程与解题思路MISC部分
    使用requests爬虫遇到的一个奇葩的问题:UnicodeEncodeError: 'latin1' codec can't encode character
    纯前端实现词云展示+附微博热搜词云Demo代码
    亚马逊精细化选品服务
    乔布斯访谈笔记
    使用腾讯云轻量级服务器
    centos 设置阿里的yum源
    云未来、新可能 绿色、无处不在、可信的计算
    OpenKruise v1.0:云原生应用自动化达到新的高峰
    服务发现与配置管理高可用最佳实践
  • 原文地址:https://www.cnblogs.com/zhao12354/p/5734679.html
Copyright © 2011-2022 走看看