随机产生小方框

HTML+CSS代码参考:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>案例--随机小方框</title>
    <style>
        .map {
            width: 800px;
            height: 600px;
            background-color: #ccc;
            position: relative;
        }
    </style>
</head>
<body>
<div class="map"></div>
</body>
</html>

JS代码参考:

// 利用自定义构造函数的方式
//产生随机数变量
(function(window){
    function Random(){

    }
    Random.prototype.getRandom(max,min){
        return Math.floor(Math.random()*(max-min)+min);
    };
    window.Random=new Random();
};)(window);
//产生小方块对象
(function(){
    //选择器的方式获取元素对象
    var map=document.querySelector("map");
    //通过构造函数创建食物
    function Food(width,height,color){
        this.width=width||20;
        this.height=height||20;
        //横纵坐标
        this.x=0;
        this.y=0;
        this.color=color;
        this.element=document.createElement("div");//小方框元素
    };
    //初始化小方框的显示效果及位置------显示在地图上
    Food.prototype.init=function(){
        //设置小方块的样式
        var div=this.element;
        div.style.position="absolute";
        div.style.width=this.width+"px";
        div.style.height=this.height+"px";
        div.style.backgroundColor=this.color;
        map.appendchild(div);//在map中添加div
        this.rander=(map);
    };
    //产生随机的位置
    Food.prototype.rander=function(map){
        //随机产生横纵坐标
        var x=Random.getRandom(0,map.offsetWidth/this.width)*this.width;
        var y=Random.getRandom(0,map.offsetHeight/this.height)*this.height;
        this.x=x;
        this.y=y;
        var div=this.element;
        div.style.left=this.x+"px";
        div.style.top=this.y+"px";
    };
    var fd=new Food(20,20,"hotpink");
    fd.init(map);
})(window);

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值