zoukankan      html  css  js  c++  java
  • 随机方块

    1:tools.js

    var Tools = {
    getRandom: function (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    }

    2:

    // 生成10个方块,随机生成颜色

    // 获取容器
    var container = document.getElementById('container');


    // 数组,存储创建的方块对象
    var array = [];
    for (var i = 0; i < 10; i++) {
    var r = Tools.getRandom(0, 255);
    var g = Tools.getRandom(0, 255);
    var b = Tools.getRandom(0, 255);

    var box = new Box(container, {
    backgroundColor: 'rgb('+ r +','+ g +','+ b +')'
    });


    // 把创建好的方块对象,添加到数组中
    array.push(box);
    }


    // 设置随机位置,开启定时器
    setInterval(randomBox, 500);

    // 页面加载完成,先设置随机位置
    randomBox();

    function randomBox() {
    // 随机生成方块的坐标
    for (var i = 0; i < array.length; i++) {
    var box = array[i];
    box.random();
    }
    }

    3:

    function Box(parent, options) {
    options = options || {};
    // 设置对象的属性
    this.backgroundColor = options.backgroundColor || 'red';
    this.width = options.width || 20;
    this.height = options.height || 20;
    this.x = options.x || 0;
    this.y = options.y || 0;

    // 创建对应的div
    this.div = document.createElement('div');
    parent.appendChild(this.div);
    this.parent = parent;

    // 设置div的样式
    this.init();
    }

    // 初始化div (方块)的样式
    Box.prototype.init = function () {
    var div = this.div;
    div.style.backgroundColor = this.backgroundColor;
    div.style.width = this.width + 'px';
    div.style.height = this.height + 'px';
    div.style.left = this.x + 'px';
    div.style.top = this.y + 'px';
    // 脱离文档流
    div.style.position = 'absolute'
    }

    // 随机生成方块的位置
    Box.prototype.random = function () {
    // 父容器的宽度/方块的宽度 总共能放多少个方块
    var x = Tools.getRandom(0, this.parent.offsetWidth / this.width - 1) * this.width;
    var y = Tools.getRandom(0, this.parent.offsetHeight / this.height - 1) * this.height;

    this.div.style.left = x + 'px';
    this.div.style.top = y + 'px';
    }

  • 相关阅读:
    hdu1828(线段树——矩形周长并)
    hdu1255(线段树——矩形面积交)
    用jQuery获取到一个类名获取到的是一个数组 ,如果对数组中的每个进行相应的操作可以这样进行
    CSS3向外扩散的圆
    鼠标放上去图片会放大
    Django分页
    Django使用富文本编辑器
    Django日志配置
    Linux中的文件类型
    Linux压缩和解压缩
  • 原文地址:https://www.cnblogs.com/pxxdbk/p/12502743.html
Copyright © 2011-2022 走看看